首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > JAVA > J2SE开发 >

Scanner 类的next()有关问题

2012-09-17 
Scanner 类的next()问题Scanner scan new Scanner(System.in)while(true){String message scan.next(

Scanner 类的next()问题
Scanner scan = new Scanner(System.in);
while(true){
String message = scan.next();
if (message.equalsIgnoreCase("exit")){
System.exit(0);
}
else{
System.out.println(message);
}
}


Scanner scan = new Scanner(System.in);
while(true){
if (scan.next().equalsIgnoreCase("exit")){
System.exit(0);
}
else{
System.out.println(scan.next());
}
}
为什么第二个程序在第二次输入的时候才有打印的结果,而第一个程序只要输入,enter之后就有结果?
求大神解释

[解决办法]
if (scan.next().equalsIgnoreCase("exit")){
System.exit(0);
}
在你比较输入的时候已经执行过一次scan.next()方法了,
System.out.println(scan.next());
然后你又调用了一次scan.next()方法,一共调用了两次next方法,
实际上要打印的是第二次输入的值!

热点排行