public class a {
public static void main(String[] args) {
// TODO: Add your code here
String str=null;
int s=0;
while(true)
{
System.out.println("请输入值:");
try
{
s = System.in.read();
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
if (s<48 || s>58)
{
System.out.println("输入值跃界!");
System.exit(0);
}
else
{
int num=s-'0';
System.out.println(num);
}
s=0;
}
}
}
运行结果:
请输入值:
3
3
请输入值:
输入值跃界!
循环第2次时,为什么没有等我输入就出现“输入值跃界!”
public static void main(String[] args) {
// TODO: Add your code here
String str=null;
int s=0;
while(true)
{
System.out.println("请输入值:");
try
{
s = System.in.read();
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
if (s<48 || s>58)
{
System.out.println("输入值跃界!");
System.exit(0);
}
else
{
int num=s-'0';
System.out.println(num);
}
s=0;
}
}
}
运行结果:
请输入值:
3
3
请输入值:
输入值跃界!
循环第2次时,为什么没有等我输入就出现“输入值跃界!”
s = System.in.read();
if (s == '\n'||s=='\r') {
continue;
}