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?
...全文
300 3 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
  • 打赏
  • 举报
回复
谢谢!原来是这样啊。
S117 2013-08-19
  • 打赏
  • 举报
回复
有空格 int num1 = Integer.parseInt(str.trim()); 这样就可以了
末日哥 2013-08-19
  • 打赏
  • 举报
回复
回车是\r\n 所以你的str里面多了一个\r c=='\n'改成c=='\r'就Ok了

62,635

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧