我有一個程序測試,看用戶輸入是否是正數和整數。 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();
}
}
}
謝謝。
分配userNum.nextInt()來如int X = userNum.nextInt(變量)而如果用x在兩個其他(X <0)和其他。 – 2013-03-04 00:14:03
我會在if語句之前將它分配給一個變量嗎?如果是的話,如果用戶輸入雙精度,這不會給我一個錯誤嗎?謝謝 – 2013-03-04 00:18:15