-1

I've a program test to see if the user input is a positive number and an integer. The if statement test if it is an integer, the else if test if it is negative. If it is a negative or a decimals, the user is asked to input a positive integer. The problem is at the else statement, it is waiting for the user input again, I want it to use the value from System.out.print("Enter the test number: "); if it pass the if and else if test.

I try assigning the user input after System.out.println("Please enter an integer!"); to an int variable but if the user input a double, I would get an error so I figured this way didn't work. Any insight on how to make the program work is appreciated, thanks!

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

Thanks.

4

2 に答える 2

0

nextIntを1回呼び出し、結果を保存して比較に使用する必要があります。

これを試して :

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 に答える