如何输入0到9之间的键盘编号?
public static void main(String[] args) {
int cars;
if (cars > 0 && cars < 9) {
Scanner sc = new Scanner(System.in);
cars = sc.nextInt();
}
System.out.println("Saisissez un entier : " + cars);
}
答案 0 :(得分:1)
首先,您必须阅读数字,然后检查数字是否在0到9之间
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int cars = sc.nextInt();
if (cars >= 0 && cars <= 9) {
System.out.println("Saisissez un entier : " + cars);
}
}
答案 1 :(得分:0)
也许使用while循环可能会有所帮助:
import java.util.Scanner;
class Main {
public static void main(String[] args) {
int userDigit = getSingleDigitIntegerInput();
System.out.println("You entered: " + userDigit);
// System.out.println("Saisissez un entier: " + userDigit);
}
private static int getSingleDigitIntegerInput() {
Scanner scanner = new Scanner(System.in);
String prompt = "Please enter a digit between 0 and 9 inclusive: ";
int validDigit = -1;
System.out.print(prompt);
while (scanner.hasNext()) {
if (scanner.hasNextInt()) {
validDigit = scanner.nextInt();
if (String.valueOf(validDigit).length() == 1) {
scanner.close();
break;
} else {
System.out.println("Error: Input number was too long");
System.out.print(prompt);
}
} else {
System.out.println("Error: Invalid input");
System.out.print(prompt);
scanner.next();
}
}
return validDigit;
}
}
用法示例:
Please enter a digit between 0 and 9 inclusive: a
Error: Invalid input
Please enter a digit between 0 and 9 inclusive: -1
Error: Input number was too long
Please enter a digit between 0 and 9 inclusive: 12345
Error: Input number was too long
Please enter a digit between 0 and 9 inclusive: 7
You entered: 7
答案 2 :(得分:0)
您现在的问题是代码中事物发生的顺序。 您首先声明一个可变汽车,但尚未赋予它任何价值 然后检查汽车是否在0到9之间 然后给汽车一个价值
您必须切换第2步和第3步,才能使逻辑正常工作
public static void main(String[] args) {
int cars; //Step 1
if (cars > 0 && cars < 9) { //Step 2
Scanner sc = new Scanner(System.in); //Step 3
cars = sc.nextInt(); //Step 3
}
System.out.println("Saisissez un entier : " + cars);
}