Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have the following method:

public void addStudent(){

    String fName, lName;
    double mGrade, fGrade;
    System.out.print("
Enter first name: ");
    Scanner in = new Scanner(System.in);
    fName = in.nextLine();
    System.out.print("
Enter last name: ");
    lName = in.nextLine();
    System.out.print("
Enter midterm grade: ");
    mGrade = in.nextDouble();
    System.out.print("
Enter final grade: ");
    fGrade = in.nextDouble();
    Student toAdd = new Student(fName, lName, mGrade, fGrade);
    students.add(toAdd);
    System.out.println("
Student record added.
");
    System.out.println(students.size());
}

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...

Thanks!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
319 views
Welcome To Ask or Share your Answers For Others

1 Answer

You can use Scanner.next() and try to parse it to the type you want (ex. to integer by using Integer.parseInt(x) and if it fails (throws and exception) try to do it again.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...