stringbuffer转为int的问题
import java.io.InputStream;
public class Hello {
public static void main(String args[]) throws Exception {
InputStream input = System.in;
StringBuffer buf = new StringBuffer();
System.out.print("请输入一个整数");
int temp = 0;
while((temp = input.read())!= -1){
char c = (char)temp;
if(c=='\n'){
break;
}
buf.append(c);
}
String str = buf.toString();
int num1 = Integer.parseInt(str);
System.out.println(num1);
input.close();
}
}
请输入一个整数1526
Exception in thread "main"
java.lang.NumberFormatException: For input string: "1526
"
at java.lang.
NumberFormatException.forInputString(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at Hello.main(Hello.java:17)
这是哪里出问题了,直接打印buf也对啊,怎么转换不成int?
------解决方案--------------------回车是\r\n
所以你的str里面多了一个\r
c=='\n'改成c=='\r'就Ok了
------解决方案--------------------有空格
int num1 = Integer.parseInt(str.trim());
这样就可以了