Don't say much, come up is dry!
? 12345678910111213141516171819202122232425262728293031323334353637 import Java.util.Scanner; public class Test_hasnextint {/** * @param args */public static void main (string[] args) {//TODO auto-generated met
Hod stub Scanner sc = new Scanner (system.in);
A solution to the infinite loop output else item after hasnextint judgment String next;
int i;
while (true) {//Scanner sc = new Scanner (system.in);
The first way to do this is to get the scanner inside and create a new scanner for Each loop. The Else statement directly prompts for the error System.out.println ("Please enter an integer");
if (Sc.hasnextint ()) {//If the next tag in this scanner input information can be interpreted as an int value in the default cardinality by using the Nextint () method, return True.
i = Sc.nextint ();
If the input 22 33 will do two times output System.out.println (i);
else {//next = Sc.next ();
The second processing method, the scanner cache in the non-int received//SYSTEM.OUT.PRINTLN ("You enter the:" + next + ", please re-enter"); Note: Next () finds and returns the next complete tag from this scanner for example, input: AA bb cc then it will receive AA first, then output AA//Then while () loop, encounter the BB in the If Judgment cache After determining that it is not an integer, the Else statement outputs the BB. The same output of CC will stop//if the input is a AA cc, then first go else output AA, and then determine that 22 is an integer go if statement, walk away again after the CC to end String nextline = SC.NEXTL
INE ();
The third way to deal with it, forget it or receive a line! SYSTEM.OUT.PRINTLN (nExtline); If you enter AAA 333 CCC first will go if the 22 receive,//and then meet AAA after walking Esls will take the whole line after receiving//Of course, normally there is no sc.hasnextint () This one Judgment,//nextline () will be the whole line
Received, and here it was because the Nextint () was taken away by a 22//So it is still necessary to see. The first one, although each input will create a scanner object, it is a reasonable solution!
Summary: Understand the cache, you will understand! }
}
}
}
The above is a small set of Java in the Hasnextint to judge the infinite cycle output else item solution, I hope to help you, if you have any questions please give me a message, small series will promptly reply to everyone. Here also thank you very much for the cloud Habitat Community website support!