Home > Software design >  How do I make a for loop ask a user for the same input again after an Exception?
How do I make a for loop ask a user for the same input again after an Exception?

Time:03-17

So to clarify, when the program asks the user for number 1: if the user were to input a letter, I need the program to tell the user that there was an input mismatch, then ask the user for number 1 again. This needs to be achieved using only one single for loop, and there can be no negative numbers that affect the sum or the average. Here's what I have so far:

import java.util.*;
import java.text.*;

class fivePositiveNumbers{
   public static void main(String[] args){
      Scanner keyboard = new Scanner(System.in);
      int userNumber;
      int sum = 0;
      System.out.println("This program will give the sum and average of 5 positive integers,");
      
      for(int i = 1; i <= 5; i  ){
         System.out.println("Enter number "   i   ": ");
         try{
            userNumber = keyboard.nextInt();
            sum = sum   userNumber;
            if(userNumber <= 0){
               throw new Exception("The integer must be positive.");
            }
         } catch(InputMismatchException e){
               System.out.println("This data type is incorrect.");
               keyboard.nextLine();
         } catch(Exception e){
               System.out.println(e.getMessage());
               keyboard.nextLine();
         }
      }
      System.out.println("The sum is "   sum   " and the average of your 5 numbers is "   sum / 5   ".");
   }
}

CodePudding user response:

Use a while or a for loop that will increment the loop count ONLY IF a valid input is provided. Your solution increments the loop counter automatically regardless of the validity of the input.

int i = 1;

while (i <= 5) {

    System.out.println("Enter number "   i   ": ");
        try{
            userNumber = keyboard.nextInt();
            if(userNumber <= 0){
                throw new Exception("The integer must be positive.");
            }
            sum = sum   userNumber; // this belongs after the negative check
            i  ; // increment the count after all validations are successfully completed
        } catch(InputMismatchException e){
            System.out.println("This data type is incorrect.");
            keyboard.nextLine();
        } catch(Exception e){
            System.out.println(e.getMessage());
            keyboard.nextLine();
        }
    }
}

If you choose to use a for loop, remove the counter increment out of the loop declaration


for (int i = 1; i <= 5;) {
    // your logic and exception handling here
    i  ; // as in the while, increment only after all validations are successfully completed
}

Another point... I don't think it is necessary to throw an exception if the number is negative. I think it is better to simply execute a continue to avoid incrementing the loop counter. This is the result of this:

This program will give the sum and average of 5 positive integers,
Enter number 1: 
-5
The integer must be positive.
Enter number 1: 
-2
The integer must be positive.
Enter number 1: 
-3
The integer must be positive.
Enter number 1: 
-4
The integer must be positive.
Enter number 1: 
-5
The integer must be positive.
Enter number 1: 
1
Enter number 2: 
2
Enter number 3: 
3
Enter number 4: 
5
Enter number 5: 
4
The sum is 15 and the average of your 5 numbers is 3.

As you can see, I entered several negative numbers and the program continued to run without incrementing the loop counter. The complete solution with continue:

public static void main(String[] args) {
      Scanner keyboard = new Scanner(System.in);
      int userNumber;
      int sum = 0;
      System.out.println("This program will give the sum and average of 5 positive integers,");
          
      for(int i = 1; i <= 5; ){
         System.out.println("Enter number "   i   ": ");
         try{
            userNumber = keyboard.nextInt();
            if(userNumber <= 0){
               System.err.println("The integer must be positive.");
               continue;
            }
            sum = sum   userNumber;
            i  ;
         } catch(InputMismatchException e){
               System.out.println("This data type is incorrect.");
               keyboard.nextLine();
         } catch(Exception e){
               System.out.println(e.getMessage());
               keyboard.nextLine();
         }
      }
      System.out.println("The sum is "   sum   " and the average of your 5 numbers is "   sum / 5   ".");
}

CodePudding user response:

class fivePositiveNumbers{
    public static void main(String[] args){
        Scanner keyboard = new Scanner(System.in);
        int userNumber;
        int sum = 0;
        System.out.println("This program will give the sum and average of 5 positive integers,");

        int ctr = 0;

        for(;;){
            System.out.println("Enter number "   (ctr 1)   ": ");
            try{
                userNumber = keyboard.nextInt();
                if(userNumber <= 0){
                    throw new Exception("The integer must be positive.");
                }
                sum = sum   userNumber;

                ctr  ;
            } catch(InputMismatchException e){
                System.out.println("This data type is incorrect.");
                keyboard.nextLine();
            } catch(Exception e){
                System.out.println(e.getMessage());
                keyboard.nextLine();
            }

            if (ctr == 5) break;
        }

        System.out.println("The sum is "   sum   " and the average of your 5 numbers is "   sum / 5   ".");
    }
}
  •  Tags:  
  • java
  • Related