user618712 user618712 - 1 year ago 80
Java Question

Checking input

I have the following method:

public void addStudent(){

String fName, lName;
double mGrade, fGrade;
System.out.print("\nEnter first name: ");
Scanner in = new Scanner(;
fName = in.nextLine();
System.out.print("\nEnter last name: ");
lName = in.nextLine();
System.out.print("\nEnter midterm grade: ");
mGrade = in.nextDouble();
System.out.print("\nEnter final grade: ");
fGrade = in.nextDouble();
Student toAdd = new Student(fName, lName, mGrade, fGrade);
System.out.println("\nStudent record added.\n");

How can I check if the user typed in something other than an integer for midterm grade and final grade? And if they entered a non-integer, I want the method to just request the user type in that value again. I'm guessing I'll have to use a do-while loop. But I don't don't know how to check the type...


Answer Source

Yes, a do-while will work best.

  int midterm;
  System.out.printLn("Enter midterm grade");
      try {
          string s = in.nextLine();
          midterm = Integer.parseInt(s);
      catch (Exception e)
          System.out.printLn("Couldn't parse input, please try again");
  while (true);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download