In java the solution of else item is output in an infinite loop after hasNextInt judgment
- 2020-05-10 18:08:14
- OfStack
No more talking, up is doing!
?12345678910111213141516171819202122232425262728293031323334353637
import 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 hasNextInt After the judgment infinite loop output else The solution to the term
String next;
int i;
while(true) {//
Scanner sc = new Scanner(System.in);
// The first 1 Method of treatment , Bring the scanner inside , Each loop is created 1 A new scanner .else It would be nice to prompt for a typo in the statement
System.out.println(" Please enter the 1 An integer ");
if (sc.hasNextInt()) { // If by using nextInt() Method in which the scanner enters the information below 1 Two tags can be interpreted as being in the default cardinality 1 a int Value, then returns true .
i = sc.nextInt();
// If it's an input 22 33 I'm going to output it twice
System.out.println(i);
} else {//
next = sc.next();
// The first 2 Method of treatment , the scanner The non in the cache int Value received off //
System.out.println(" What you typed is :" + next + ", Please re-enter ");
// Pay attention to :next() Locate and return the following from this scanner 1 Full mark For example, the input : aa bb cc So this is going to receive first aa , Then the output aa
// then while() cycle , encounter if Determine what's in the cache bb Make sure it's not an integer and continue else Statement output bb. Same output cc stops
// If I put in a aa 22 cc, Then go first else The output aa, And let's see 22 Go is an integer if statements , Walk again after walking cc To the end
String nextLine = sc.nextLine();
// The first 3 Method of treatment , Forget it Or receive 1 ok !
System.out.println(nextLine);
// If the input 22 aaa 333 ccc The first 1 Time will go if the 22 Receive off ,
// And then meet aaa After the walk esls It's going to take in the whole of the rest of the line
// Of course, , Not normally sc.hasNextInt() this 1 It's time to judge ,
//nextLine() It's going to take in the whole row , And this is because it's up here nextInt() Took the 1 a 22
// So let's see . The first 1 The seed is created every time it is entered 1 time Scanner object , But it's also 1 A reasonable solution !
// conclusion : Understand the cache , You'll see !
}
}
}
}