2013-03-04 64 views
-1

我有一個程序測試,看用戶輸入是否是正數和整數。 if語句測試它是否是整數,else if測試它是否定的。如果它是負數或小數,則要求用戶輸入正整數。問題在於else語句,它正在等待用戶再次輸入,如果它通過if和else if測試,我希望它使用System.out.print("Enter the test number: ");中的值。Java if-else comparison

我嘗試將System.out.println("Please enter an integer!");後面的用戶輸入分配給一個int變量,但如果用戶輸入一個double,我會得到一個錯誤,所以我想通過這種方式不起作用。任何關於如何使程序工作的見解表示讚賞,謝謝!

import java.util.Scanner; 

public class FibonacciNumbersTester 
{ 
    public static void main(String[]args) 
    { //Variables 
     Scanner userDed = new Scanner(System.in); 
     String userChoice = "Y"; 
     while(userChoice.equalsIgnoreCase("Y")) 
     { 
      Scanner userNum = new Scanner(System.in); 
      System.out.print("Enter the test number: "); 
      if(!userNum.hasNextInt()) 
      { 
       System.out.println("Please enter an integer!"); 
      } 
      else if(userNum.nextInt() < 0) 
      {  
       System.out.println("Please enter a postive integer!"); 
      } 
      else 
      { 
       int NumTo = userNum.nextInt(); 
       System.out.println(NumTo); 
      } 

      System.out.print("Would you like to continue? (Y/N)"); 
      userChoice = userDed.next();     
     } 
    } 
} 

謝謝。

+0

分配userNum.nextInt()來如int X = userNum.nextInt(變量)而如果用x在兩個其他(X <0)和其他。 – 2013-03-04 00:14:03

+0

我會在if語句之前將它分配給一個變量嗎?如果是的話,如果用戶輸入雙精度,這不會給我一個錯誤嗎?謝謝 – 2013-03-04 00:18:15

回答

0

您應該致電nextInt一次,保存結果並將其用於比較。

嘗試這種情況:

public static void main(String[] args) { // Variables 
     Scanner userDed = new Scanner(System.in); 
     String userChoice = "Y"; 
     while (userChoice.equalsIgnoreCase("Y")) { 
      Scanner userNum = new Scanner(System.in); 
      System.out.print("Enter the test number: "); 
      if (!userNum.hasNextInt()) { 
       System.out.println("Please enter an integer!"); 
      } else { 
       int NumTo = userNum.nextInt(); 
       if (NumTo < 0) 
        System.out.println("Please enter a postive integer!"); 
       else 
        System.out.println(NumTo); 

      } 
      System.out.print("Would you like to continue? (Y/N)"); 
      userChoice = userDed.next(); 

     } 
    } 
+0

Iswanto,非常感謝你!不敢相信我沒有想到這個!過去8小時一直在改變我的計劃,在這裏你正在拯救我的生命。謝謝! – 2013-03-04 00:25:11

0
Pattern positiveInt = Pattern.compile("^[1-9]\d*$"); // for positive integer 
if(!userNum.hasNext(positiveInt)) { 
    System.out.println("Please enter an positive integer (greater than 0) !"); 
} 
else { 
    int NumTo = userNum.nextInt(positiveInt); 
    System.out.println(NumTo); 
}