vendredi 14 octobre 2016

Scanner won't allow me to continue after fixing an invalid response

So I've written a test class to test a program that will allow me to take in number of courses, letter grades, and course credits and then calculate total weighted points, total credits, and GPA within a loop designed for 3 courses max.

However, I need to validate the number of courses and prove that it will run after both an invalid and valid input have been entered.

I've gotten it so that will prompt the user for a valid number of courses after an invalid response, but once the valid response is input the program just stops instead of running like it is supposed to. Can anyone tell me why?

Here's my code:

import java.util.*;
import java.lang.*;

public class ComputeGpa
{ 
   public static void main(String [] args)
   {
      Gpa grades1 = new Gpa();

      Scanner in = new Scanner (System.in);

      System.out.println("Enter number of courses: ");
      int courses = in.nextInt();
      if(courses > 0)
      {
        int i = 0;
        while(i < 3)
        {  
           System.out.println("Please enter a letter grade.");
           String letter = in.next();
           char result = letter.charAt(0);

           System.out.println("How many credits was this class worth?");
           int credits = in.nextInt();

           grades1.addToTotals(result, credits);
           i++;
        }
        System.out.printf("GPA: %.2f", grades1.calcGpa());
      }
      else
      {
        System.out.println("Number of courses must be greater than 0. Please enter a valid number of courses.");
        courses = in.nextInt();
      }        
    }
} 

The output for that is as follows:

Enter number of courses: 
-2
Number of courses must be greater than 0. Please enter a valid number of courses.
3

And then the program stops running. Where Am I going wrong? I thought the in.next() on the letter String would fix this problem but apparently I was wrong. Any ideas?

Aucun commentaire:

Enregistrer un commentaire