import java.util.*;
public class Practice {
public static String prompt = "How are you? ";
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
System.out.print(prompt);
//int year=getYourAge(console);
System.out.println("Your age is "+getYourAge(console));
}
public static int getYourAge(Scanner console){
while(!console.hasNextInt()){
console.next();
System.out.println("Not an integer;try again!");
System.out.print(prompt);
}
return console.nextInt();
}
}
我想问的是,当程序运行到return语句的时候,为什么不等待新的一次输入呢?
这是某次我的运行结果,为什么我输入18之后,到了return语句,不等待
我新的一次输入?平时无论何时运行类似的nextInt()语句都会等待输入的。
我哪里理解出错了?
什么叫做不等待新的输入?lz的程序执行完一遍就结束了(当读到有符合的int值后)
console.hasNextInt() 代表要有int型,你输入字母console.hasNextInt()为false,非后就为true,然后你就无限进入循环,直到你输入18后console.hasNextInt()为true,非后为false,跳出循环运行return,这是你程序的运转。重点来了有 Scanner console = new Scanner(System.in)这句,那么你任何一次输入都会放到console中,以前没有输入数字所有console.hasNextInt()就没有int,你输入后就跳出了
等待了,然后接收到你输入的18后就返回了。
hasNextInt判断的是输入的是否是int类型,next()是返回字符串。一开始你输入的是精度型的字符串18.7,所以不符合haNextInt的条件,while循环会继续执行。当你输入18的时候那么就是int类型了,hasNextInt返回的就是true,那么就不会进入while循环。
hasNextInt应该只是判断,没有把scanner往后移一位吧
你应该多写几种代码,然后前后对比,你把你程序中的console.next();去掉后,你会发现不会等待你再次输入,会一直输出"Not an integer;try again!",原因就是console里有值,console.next()的作用就是取出值,当console里没值时,运行到console.hasNextInt()会阻塞,等待你输入,这样的答案在结合你的问题看看就明白了吧。