lundi 8 novembre 2021

if else condition is not executed properly

I have a condition where if the user inputs a negative number or a number which is more than 100, or a string, an error message should be printed "That wasn't a valid percentage, I need a number between 0-100. Try again." and ask the user to reenter a valid number. and if the user decided to just enter, all the input should be calculated and printed the average amount.


   public static void main(String[ ] args) {
   
      int count = 0; //count to stop loop
       
      double[ ] aGrade = new double[SIZE]; 
      String input = new String("");
      Scanner scan = new Scanner(System.in);
      double total = 0; 
      int gTotal = aGrade.length; 
      boolean exit = false; 
      while ((count < SIZE) && (!exit)) {
      
         System.out.print("Enter number " + (count + 1) + ": " + "\n");
         try {
            input = scan.nextLine();
         
            if (Double.parseDouble(input) > 0 && Double.parseDouble(input) < 100) {
               aGrade[count] = Double.parseDouble(input); //put into the array
               count++; //only increment count if success

            } else 
               System.out.println("That wasn't a valid percentage,"
                  + " I need a number between 0-100. Try again.");
         
         } catch (NumberFormatException nfe) {
            exit = true; //exit loop
         }
      }

      System.out.println("number of grades entered: " + count + "\n");
      for (int i = 0; i < count; i++) { 
      
      
      // print entered grade
         System.out.println("grade " + (i + 1) + ": " + aGrade[i]);   
      }
      for (int i = 0; i < count; i++) {
         total += aGrade[i]; 
      }
   // calculate and print the average
      System.out.println("\n" + "Average grade: " + total /count);  
   

But when I run my code, if I input letters, it won't allow the user to reinput value but prints whatever is calculated. I think it is in my if-else statement, but I am not sure how

Aucun commentaire:

Enregistrer un commentaire