當我輸入一個小於12的數字時沒有問題,但是當我輸入更大的數字時,我得到「輸入一個小於13的數字」並始終在後續投入。我怎樣才能讓程序檢查int和小於13的數字?無法檢查用戶輸入是否小於某個數字
package com.company;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
Scanner z = new Scanner(System.in);
boolean cont;
boolean isNumber;
do {
System.out.println("Enter the number you want to see the factorial of (0-12)");
do{
if(s.hasNextInt()){
isNumber = true;
}else{
isNumber=false;
System.out.println("Enter a number");
s.next();
}
}while(!isNumber);
int input = s.nextInt();
boolean isSmall;
do{
if(input < 13){
isSmall= true;
}else{
isSmall=false;
System.out.println("Enter a number less than 13");
s.next();
}
}while(!isSmall);
int factorial = 1;
System.out.print(input + "!" + " = ");
for (int i =1 ; i<=input ; i++) {
factorial *= i;
System.out.print(i);
if (input == i) {
break;
}
System.out.print(" * ");
}
System.out.println(" = " + factorial);
System.out.println("Do you want to continue?");
String line = z.nextLine();
if(line.matches("y|YES|Y|yes|Yes")){
cont=true;
}else{
cont= false;
System.out.println("Thanks for using the program!");
}
}while(cont);
}
}
在進行下一次比較之前,您沒有閱讀下一個int。我建議創建一個getNumberMethod,它可以具有所有必需的邏輯。 –