0

Could someone explain to me how I could put a conditional of grade can only be 0 or greater or 100 or less. I've tried the statement inside the while loop, but then the average doesn't come out correct. I've put it outside the loop, but that doesn't seem to work either.

 while (!gradeInput.equals(SENTINEL)) {

         try {
            int grade = Integer.parseInt(gradeInput);


            sum += grade;
            count++;

         }
         catch (NumberFormatException e) {
            JOptionPane.showMessageDialog(null,"Error! only numeric values.");
         }


         gradeInput = JOptionPane.showInputDialog("Enter exam grade (or -1 to end the program):");
      }
1

3 Answers 3

1

The comment from Sharma is probably cleaner, but this should work too:

gradeInput calculation should be at the beginning of the loop - not the end.

Then put your validation inside the loop like this (only summing and counting if the input is valid)

if(grade>0 && grade <100) {
        sum += grade;
        count++;
}

Then calculate the average outside the loop with a sum/count

Sign up to request clarification or add additional context in comments.

Comments

0
 while (!gradeInput.equals(SENTINEL)) {

     try {



        int grade = Integer.parseInt(gradeInput);
if(grade==0 || grade<=100){

        sum += grade;
        count++;
}
     }
     catch (NumberFormatException e) {
        JOptionPane.showMessageDialog(null,"Error! only numeric values.");
     }


     gradeInput = JOptionPane.showInputDialog("Enter exam grade (or -1 to end the program):");
  }

Comments

0

Try this

while (!gradeInput.equals(SENTINEL)) {
         try {
            int grade = Integer.parseInt(gradeInput);
            if(grade>=0 && grade<=100){
               sum += grade;
               count++;
            }
         }
         catch (NumberFormatException e) {
            JOptionPane.showMessageDialog(null,"Error! only numeric values.");
         }
         gradeInput = JOptionPane.showInputDialog("Enter exam grade (or -1 to end the program):");
      }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.