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.