简体   繁体   中英

Java - Error message to display

I have to add validation so that once the user enters a number that's not 0-100 inclusive, it shows an error message. My question is, do I just have to enter one simple line or do I need to enter something after each prompt to validate the entry? (I might just be overthinking this, as my brain is gone with the birds today) What follows is the block that I need to adjust.

 switch(choice)
        {
            case 1:
            System.out.println("Entering Student Details");
            System.out.println("------------------------");
            System.out.print("   Student name:                               ");
            name = sc.nextLine();
            sc.nextLine();
            System.out.print("   Student number:                             ");
            stuNum = sc.nextLine();
            System.out.print("   class 0 grade:             ");
            grade = sc.nextInt();
            System.out.print("   class 1 grade:                  ");
            grade2 = sc.nextInt();
            System.out.print("   class 2 grade:                           ");
            grade3 = sc.nextInt();
            System.out.print("   class 3 grade:                          ");
            grade4 = sc.nextInt();
            System.out.print("   class 3 grade:              ");
            grade5 = sc.nextInt();
            System.out.print("   class 4 grade:                      ");
            grade6 = sc.nextInt();
        }
    }while(choice != 0);

    System.out.println("Thank you for using the system.");

You would need to validate each input after the user inputs it. If there is an error you should send an error message to the user and ask for a different input for that grade and continue looping until a valid input is received. This may be better to put in another method in order to split up functionality. You could create a new method called getUserInput() that has a loop in it and asks user for input until a valid input is received.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM