Java if-else比较

时间:2013-03-04 00:06:31

标签: java

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

我尝试将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();                
        }  
    }  
}  

感谢。

2 个答案:

答案 0 :(得分: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();

        }
    }

答案 1 :(得分: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);  
}