尽管其他答案为您提供了使用循环的正确思路,但您应避免将异常用作基本逻辑的一部分。相反,您可以使用
hasNextIntfrom
Scanner检查用户是否传递了整数。
System.out.print("enter number: ");while (!scanner.hasNextInt()) { scanner.nextLine();// consume incorrect values from entire line //or //tastiera.next(); //consume only one invalid token System.out.print("enter number!: ");}// here we are sure that user passed integerint value = scanner.nextInt();


