我正在尝试制作一个用户需要输入随机整数的程序。如果用户输入字符串,我希望弹出错误消息:“这不是数字”,然后重启程序,直到用户输入数字为止。到目前为止我已经知道了,但是我被卡住了。如果我输入一个字符串并且程序崩溃,我只会收到一条错误消息。
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int number = 0;
do {
System.out.println("Input a number!");
number = scanner.nextInt();
if (!scanner.hasNextInt()) {
System.err.println("This is not a number");
}
} while (!scanner.hasNextInt());
System.out.println("You entered: " + number);
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String input = "";
int number = 0;
boolean end = true;
do {
System.out.println("Input a number!");
input = scanner.nextLine();
try {
number = Integer.parseInt(input);
end = true;
} catch(Exception e) {
System.err.println("This is not a number");
end = false;
}
} while (!end);
System.out.println("You entered: " + number);
}
public class Solution {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String number;
do {
System.out.println("Input a number!");
number = scanner.next();
} while (!isNumeric(number));
System.out.println("You entered: " + number);
}
public static boolean isNumeric(final String str) {
// null or empty
if (str == null || str.length() == 0) {
return false;
}
return str.chars().allMatch(Character::isDigit);
}
}
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int number = 0;
boolean valid;
do {
valid = true;
System.out.print("Input an integer: ");
try {
number = Integer.parseInt(scanner.nextLine());
} catch (NumberFormatException e) {
System.out.println("This is not an integer. Try again.");
valid = false;
}
} while (!valid);
System.out.println("You entered: " + number);
}
}
示例运行:
Input an integer: a This is not an integer. Try again. Input an integer: 12.34 This is not an integer. Try again. Input an integer: 45 You entered: 45
注意:
使用Scanner:nextLine
代替Scanner::nextInt
;特别是在循环处理输入时。检查Scanner is skipping nextLine() after using next() or nextFoo()?了解更多信息。[
scanner.hasNextInt()
应在scanner.nextInt()
之前使用,即 if(scanner.hasNextInt()) {
number = scanner.nextInt();
}
如果要输入任何数字(不仅是整数),请使用
number = Double.parseDouble(scanner.nextLine());
,但请确保将number
声明为double
变量,即声明为double number = 0.0
。