您可以使用hasNextInt()來驗證從正INT輸入。
import java.util.Scanner;
public class Test2 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int userInput = 0 ;
do {
System.out.println("Please enter a number from 2 to 100");
while (!sc.hasNextInt()) {
System.out.println("That's not a number!");
sc.next();
}
userInput = sc.nextInt();
if(userInput<2 || userInput > 100) {
break;
}
System.out.println(userInput);
} while (userInput <= 1 || userInput >= 100);
}
}
您將得到更好的主意,如果你可以按照下面的例子programs.The經歷顯示java.util.Scanner.hasNext()方法的使用。
import java.util.*;
import java.util.regex.Pattern;
public class ScannerDemo {
public static void main(String[] args) {
String s = "Hello World! 3+3.0=6";
// create a new scanner with the specified String Object
Scanner scanner = new Scanner(s);
// check if the scanner has a token
System.out.println("" + scanner.hasNext());
// print the rest of the string
System.out.println("" + scanner.nextLine());
// check if the scanner has a token after printing the line
System.out.println("" + scanner.hasNext());
// close the scanner
scanner.close();
}
}
輸出
真,世界,你好! 3 + 3.0 = 6,假
你不要求*用戶名*,所以我想你談論了*用戶輸入*。基本上,你想要求用戶輸入一些輸入,直到找到有效的輸入爲止。 – Al1
你在說什麼用戶名?從1到10(或根據您的代碼2到100)的數字應該是用戶名嗎? –
可能的重複https://stackoverflow.com/q/46590539/4906586 – Al1