java数据格式异常

来源:百度知道 编辑:UC知道 时间:2024/09/20 23:33:20
这个程序的功能是输入投资额,投资年限,然后计算每年总收入,能编译,但是在输入年限str2按Enter之后提示数据格式错误,请帮忙看一下,谢谢!
import java.io.IOException;
class Investment
{
public static void main(String [] args) throws IOException
{
String str1=new String();
String str2=new String();

System.out.println("请输入您的投资金额:");
char tr1=(char)System.in.read();
while(tr1>='0' && tr1<='9')
{
str1=str1+tr1;
tr1=(char)System.in.read();
}

System.in.read();
int e1=Integer.parseInt(str1);
System.out.println("您输入的金额为:"+e1);
System.out.print("请按”Enter“键确认!");
System.in.read();
System.out.println("请输入您的投资年限:");
char tr2=(char)System.in.read();
while(tr2>='0' && tr2&

输入回车时会返回 “回车”“换行”两个字符
在进行下次输入时应该把这两个字符都读出来
改为
System.out.print("请按”Enter“键确认!");
System.in.read(); //读回车
System.in.read(); //读换行
System.out.println("请输入您的投资年限:");


System.out.print("请按”Enter“键确认!");
while(System.in.read() != 10); //循环直到读到换行
System.out.println("请输入您的投资年限:");

str1那里循环体里读了一个非数字字符,也就是回车,tr1>='0' && tr1<='9判断为false,才退出循环

从string到int型的 应该捕获异常!!