public class Test {
public static void main(String[] args) {
// TODO Auto-generated method stub
byte[] buf=new byte[10];
try{
System.in.read(buf);
}catch(Exception e){
e.printStackTrace();
}
String str=new String(buf);
System.out.println(str);
int num=Integer.parseInt(str);
System.out.println(num);
}
}
该程序执行后报java.lang.NumberFormatException:For input string:"3"
这是为什么啊,如果我把str=“123”,这个时候是正确的,难道是我的输入不对吗?
问题在这里
你只在控制台输入了3个数字。
而buf有10个位置。
public static void main(String[] args) {
// TODO Auto-generated method stub
byte[] buf=new byte[3];
try{
System.in.read(buf);
}catch(Exception e){
e.printStackTrace();
}
String str=new String(buf);
System.out.println(str);
int num=Integer.parseInt(str);
System.out.println(num);
}
}
再试试输入"123"
所以变成字符串之前要去掉public static void main(String[] args) throws UnsupportedEncodingException {
// TODO Auto-generated method stub
byte[] buf = new byte[10];
int inputLength = 0;
try {
inputLength = System.in.read(buf) - 2;
} catch (Exception e) {
e.printStackTrace();
}
String str = new String(buf,0,inputLength);
System.out.println(str);
int num = Integer.parseInt(str);
System.out.println(num);
}
更主要的是byte[] buf=new byte[10]; 定义的数组长度为10,在输入值少于10的时候,转成String时,没有输入值的部分变成了" "所以需要把int num=Integer.parseInt(str);
改成int num=Integer.parseInt(str.replace("\r\n", "").trim());
没有初始化的byte[], 其值==0,
所以直接new String(buf), 那些部分变成方块而已,也就属0x0 , 不过那个trim() 可以把这些去掉。