Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking input type...how?

Tags:

java

I have the following method:

public void addStudent(){

    String fName, lName;
    double mGrade, fGrade;
    System.out.print("\nEnter first name: ");
    Scanner in = new Scanner(System.in);
    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);
    students.add(toAdd);
    System.out.println("\nStudent record added.\n");
    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!

like image 494
user618712 Avatar asked Apr 19 '26 03:04

user618712


1 Answers

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.

like image 85
Argote Avatar answered Apr 20 '26 17:04

Argote



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!