关于system.in.read()的问题

[复制链接]
查看11 | 回复1 | 2006-8-16 22:23:00 | 显示全部楼层 |阅读模式
请问如下代码
import java.io.*;
class Sumx
{ int s=0,x=0;
boolean flag=true;
public int readInt()
{
int a=1;
while(flag)
{
try
{
x=System.in.read();
}
catch (Exception e)
{
System.out.println(e.getMessage());
}
switch(x)
{
case '\r':
case '\n':
flag=false;
break;
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
s=s*10+(x-'0');
break;
default:
System.out.println("输入了错误的数据 &quot

;
flag=false;
}

}
return s;
}
public static void main(String[] args) throws Exception
{
int x,y;
Sumx s=new Sumx();
System.out.println("请输入 X 的值&quot

;
x=s.readInt();
System.out.println("请输入 Y 的值&quot

;
x=s.readInt();
System.out.println( x+" + "+y+ " 的和值是 : "+(x+y));
}
}

程序第二次输值时为什么不能执行?
回复

使用道具 举报

千问 | 2006-8-16 22:23:00 | 显示全部楼层
帮楼主改了一下,你试下可以运行成功的。(改的地方标记了,你应该能看懂的)
import java.io.*;
class Sumx
{
public int readInt()throws Exception
{
boolean flag=true; //此处修改
int s=0,x=0;
//System.out.println(" flag= "+flag+" s="+s+" x="+x);
while(flag)
{
try
{
x=System.in.read();
//System.out.println("x="+x);
}
catch (Exception e)
{
System.out.println(e.getMessage());
}
switch(x)
{
//case 10:
case '\n':
case '\r':
flag=false;
break;
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
s=s*10+(x-'0');
break;
default:
System.out.println("输入了错误的数据 &quot

;
flag=false;
}
}
System.in.skip(1); //此处修改
return s;
}
public static void main(String[] args) throws Exception
{
int x,y;
Sumx s=new Sumx();
System.out.println("请输入 X 的值&quot

;
x=s.readInt();
System.out.println("请输入 Y 的值&quot

;
y=s.readInt(); //此处修改
System.out.println( x+" + "+y+ " 的和值是 : "+(x+y));
}
}
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

主题

0

回帖

4882万

积分

论坛元老

Rank: 8Rank: 8

积分
48824836
热门排行