62,621
社区成员
发帖
与我相关
我的任务
分享
import java.io.UnsupportedEncodingException;
import java.util.Scanner;
public class IntToChar {
public static final int MINIMUM = 32;// 最小的可显字符
public static final int MAXIMUM = 256;// 最小的可显字符
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int x = MINIMUM;//赋初值
System.out.println("请输入32--255之间的数,\"exit\"退出!");
String input = scan.nextLine();
while (true) {
try {
x = Integer.parseInt(input);
} catch (NumberFormatException nee) {
//nee.printStackTrace();
System.out.println("输入数据 \"" + x + "\"非法,请从新输入!");
continue;
}
if (x <= MINIMUM || x >= MAXIMUM) {
System.out.println("输入数据 \"" + x + "\"超出范围!");
} else {
System.out.println("" + x + " --> " + changeIntToString(x));
}
System.out.println("请输入32--255之间的数,\"exit\"退出!");
input = scan.nextLine();
if(input.equals("exit")) {
break;
}
}
}
/**
* 把Int 型数,转换成字符。
*
* @param x
* @return x 所对应的字符。
*/
public static String changeIntToString(int x) {
byte[] b = new byte[1];
String result = "";
b[0] = (byte) x;
try {
result = new String(b, "ISO-8859-1");
} catch (UnsupportedEncodingException uee) {
uee.printStackTrace();
}
return result;
}
}
int[] arr = {1,65,78};
byte[] bits = new byte[arr.length];
for(int i = 0; i < bits.length; i++){
bits[i] = (byte)arr[i];
}
String str = new String(bits);
System.out.println(str);