If a user inputs an invalid character how can I get my program to output a message to the user and re ask the question?

Hi,

In my java program, if the user enters the wrong character such as “E” or “A” in my program how can I output a message to the user? The line which I’m speaking about in my program is when the user has to choose to input one out of three characters P, M or D. However, if the user inputs another character which isn’t listed I want the program to display a message.

As you can see if the user inputs “E” the program skips to the next step. However, I want the user to be notified and asked again to enter the correct value which is “P, M or D”.

In order to do what I’m trying to achieve I believe I need to do an if statement so here what I have tried.

if((i = P,M,D) && (i < ?)) {
   System.out.println("ERROR, please input only P,M or D.");
}

Screenshot of the program

JAVA CODE

        String grade;
        int yr2cred[] = new int[18];
        char yr2grade[] = new char[18];
        for (int i = 1; i <= 18; i++) {
            System.out.println("Please enter your grade for unit " + i +" "+(username) + ".");
            grade = userinput.next();
            yr2grade[i - 1] = grade.charAt(0);
            if (yr2grade[i - 1] == 'P' || yr2grade[i - 1] == 'p') {
                yr2cred[i - 1] = yr2cred[i - 1] + P;
            }
            if (yr2grade[i - 1] == 'M' || yr2grade[i - 1] == 'm') {
                yr2cred[i - 1] = yr2cred[i - 1] + M;
            }
            if (yr2grade[i - 1] == 'D' || yr2grade[i - 1] == 'd') {
                yr2cred[i - 1] = yr2cred[i - 1] + D;
            }
        }

perhaps a dropdown menu, with options to force the input to be correct if that’s a possibility - or maybe some sort of while loop…

do {
 get new input
 if (inputInvalid) {
   "display an invalid message" 
 } 
} while (inputInvalid)

i know that’s pretty vague but it’s not nothing

I think the DO-WHILE loop fits the best for your case.
The code for it would be something like:

do {
    // get the userinput
} 
while (input != 'P' || input != 'M' || input != 'D');

The loop will iterate again and again until the condition inside the while loop is met . i.e until the preferred character is inputted. Then it will exit the loop and go to the following lines of code.

Hi, any chance you can put my code into the DO-WHILE loop as I keep getting error for some reason? Thanks for your feedback post.

do {
    System.out.println("Provide your input");
    grade = userinput.next();
}
while (grade != 'P' || grade != 'M' || grade != 'D');

This is the general pattern and it should work on java as well.

Btw I dont know what is with your link . You are writing java in Html file. Moreover, I guess jsfiddle is just for javascript.