-1

我有一个程序测试,看看用户输入是否是正数和整数。该if语句测试是否为整数,else if测试是否为负。如果是负数或小数,则要求用户输入正整数。问题出在 else 语句中,它再次等待用户输入,我希望它使用System.out.print("Enter the test number: ");if 它通过 if 和 else if 测试的值。

我尝试将用户输入分配System.out.println("Please enter an integer!"); 给一个 int 变量,但如果用户输入一个双精度,我会收到一个错误,所以我认为这种方式行不通。任何有关如何使程序工作的见解都值得赞赏,谢谢!

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();                
        }  
    }  
}  

谢谢。

4

2 回答 2

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();

        }
    }
于 2013-03-04T00:18:25.930 回答
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);  
}
于 2013-03-04T00:29:27.460 回答