In an assignment for my intro to programming course which uses java, I have written an input validation loop which executes as expected in Dr.Java (the IDE they have requested us to use) but when an invalid input is entered when running in command line, or eclipse, the program goes into an infinite loop as pictured here.
While hand tracing the loop it seems that everything should work as intended. Is there something I am missing here?
I know this can be written by trying and catching an exception, but it was requested that we validate input using the in.hasNextDouble() for our scanner.
while(diameterInputLoop == false)
{
/***********************************************************************************************
* Initialize the Scanner in at the beginning of the loop
* because invalid inputs will close the scanner to clear it
***********************************************************************************************/
Scanner in = new Scanner(System.in);
/***********************************************************************************************
* Prompt for Diameter
***********************************************************************************************/
System.out.print("Enter the jelly bean diameter in cm: ");
/***********************************************************************************************
* If statement to verify if a number was entered
* with a nested if statement to check if the value is less than or equal to zero
* If no number is entered, repeat the input loop
***********************************************************************************************/
if(in.hasNextDouble())
{//start valid number if statement
jellyBeanDiameter = in.nextDouble();
//set controller to true, exiting loop
diameterInputLoop = true;
// check for positive numbers
if(jellyBeanDiameter > 0 )
{
//if diameter is positive, set loop controller to true to exit loop
diameterInputLoop = true;
}
//if a negative number is entered
else
{//start negative check
//print error for negative & 0 numbers
System.out.println("Error: invalid input, diameter must be a number greater than zero");
//close scanner
in.close();
//reset diameter value
jellyBeanDiameter = 1.0;
//set controller to false to repeat loop
diameterInputLoop = false;
}//end negative if check{
}//end valid number if statement
//if a number was not entered
else
{
//print error asking for number
System.out.println("Error: invalid input, diameter must be a number.");
//close scanner
in.close();
//reset diameter value
jellyBeanDiameter = 1.0;
//set controller to false telling loop to repeat
diameterInputLoop = false;
}//end else
}//end while loop
Aucun commentaire:
Enregistrer un commentaire