2017-07-17 202 views
0

當我輸入一個小於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); 
    } 
} 
+3

在進行下一次比較之前,您沒有閱讀下一個int。我建議創建一個getNumberMethod,它可以具有所有必需的邏輯。 –

回答

0

你不讀下一INT在你的第二個do-while循環再比較之前。我建議創建一個單獨的方法來檢索一個有效的數字。

private static int getValidInt(Scanner s) { 
    System.out.println("Enter the number you want to see the factorial of (0-12)"); 

    int input = getInt(s); 
    while (input < 0 || input > 12) { 
     System.out.println("Enter an integer between 0 and 12."); 
     s.next(); 
     input = getInt(s); 
    } 
    return input; 
} 

private static int getInt(Scanner s) { 
    while (!s.hasNextInt()) { 
     System.out.println("Enter a number"); 
     s.next(); 
    } 

    return s.nextInt(); 
} 

然後你就可以刪除2內DO-while循環,並與int input = getValidInt(s);

更換這也將確保輸入始終是一個int大於0,你的代碼失蹤儘管消息指出這是一個要求。

0

您需要在輸入警告後真正將輸入設置爲輸入的數字。現在,你只是不斷循環,因爲無論輸入什麼內容,輸入都保持不變。

 boolean isSmall; 
     do { 
      if (input < 13) { 
       isSmall = true; 

      } else { 
       isSmall = false; 
       System.out.println("Enter a number less than 13"); 
       input = s.nextInt(); 

      } 
     } while (!isSmall); 
1

你忘了把新值的輸入,所以你總是比較值大13

do{ 
    if(input < 13){ 
     isSmall= true; 
    }else{ 
      isSmall=false; 
      System.out.println("Enter a number less than 13"); 
      input = s.nextInt(); 
     } 
    }while(!isSmall); 
相關問題