Without further ado, I just do it!
?12345678910111213141516171819202122232425262728293031323334353637import java.util.Scanner; public class Test_hasNextInt { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub Scanner sc = new Scanner(System.in); // About the solution to the infinite loop output of the else item after hasNextInt judgment String next; int i; while(true) {// Scanner sc = new Scanner(System.in); //The first method is to take the scanner into it. Each loop creates a new scanner. The input error is just prompted in the else statement. System.out.println("Please enter an integer"); if (sc.hasNextInt()) { //If by using the nextInt() method, the next mark in the scanner input information can be interpreted as an int value in the default cardinality, then true is returned. i = sc.nextInt(); //If it is input 22 33, it will output twice System.out.println(i); } else {// next = sc.next(); //The second processing method is to receive the non-int value in the scanner cache // System.out.println("You entered:" + next + ", please re-enter"); //Note: next() looks for and returns the next complete mark from this scanner, for example input: aa bb cc, then aa will be received first, and then output aa // Then while() loop, and if you judge that the bb in the cache is not an integer, then continue to go to the else statement to output bb. Similarly, it will stop after outputting cc. If the input is aa 22 cc, then go first else to output aa, then determine if 22 is an integer or if statement, and walk again to end String nextLine = sc.nextLine(); //The third method, forget it, just accept a line! System.out.println(nextLine); //If you enter 22 aaa 333 ccc, the first time you will go if you receive 22, // Then when you encounter aaa and walk esls, you will receive the entire line after it//Of course, under normal circumstances, there is no sc.hasNextInt() as a judgment, //NextLine() will receive the entire line, and this is because a 22 is taken away by nextInt() above. //So it depends on what to do. Although the first type will create a Scanner object every time you input, it is also a reasonable solution! //Summary: Understand the cache and you will understand! } } } } }The above is the solution to the hasNextInt judgment in Java introduced to you by the editor. I hope it will be helpful to you. If you have any questions, please leave me a message and the editor will reply to you in time. Thank you very much for your support to Wulin.com website!