Question:

I need help with Java!

by  |  earlier

0 LIKES UnLike

I am trying to establish a loop that handles exceptions while receiving input from the user. I need to get 5 values and I need to have them repeat the input if an error is caught. I am using a while loop to do this, and for the most part it works. I have a problem. If I enter the first value in incorrect format it will tell me the error and allow a re-enter. The problem is when I enter the first value correctly, and then an erroneous second, third, fourth value, it will skip right through to the end of the program without letting me finish entering the values. My error is somewhere in this block of code:

while(!validInput)

{

try

{

for(item = 0 ; item < priceArray.length; item )

{

System.out.println("Enter a price: ");

inputPrice = Double.parseDouble(stdin.readLine());

priceArray[item] = inputPrice;

validInput = true;

}

}

catch(IOException re)

{

System.out.println(re.getMessage() "There was an IO exception.");

}

catch(NumberFormatException ne)

{

System.out.println( ne.getMessage()

" is not a valid format for an integer." );

}

}

 Tags:

   Report

1 ANSWERS


  1. There&#039;s a few problems here.  The biggest though is you have your while/for loops inside out.  What you want to do is this (I&#039;m using &#039;.&#039; to preserve the formatting):

    for (int item = 0; item &lt; priceArray.length; item++) {

    ...validInput = false;

    ...while (!validInput) {

    ......try {

    .........System.out.print( &quot;Enter a price: &quot;);

    .........priceArray[item] = inputPrice;

    .........validInput = true;

    ......} catch (IOException re) {

    .........System.out.println( re.getMessage());

    ......} catch (NumberFormatException ne) {

    .........System.out.println( ne.getMessage());

    ......}

    ...}  // end of while

    } // end of for

You're reading: I need help with Java!

Question Stats

Latest activity: earlier.
This question has 1 answers.

BECOME A GUIDE

Share your knowledge and help people by answering questions.