java - Check If String Input Is Not Equal To An Array of Strings -
my current issue checking how create condition output invalid input when user's input not equal of strings in defined array, , continuously ask new input until valid option.
code:
public class gamemenu { static string choice; int useroption = 0; public void printmainmenu() { [...] /* other code prints out menu */ checkifguesscomputernumberischosen(); } private void checkifguesscomputernumberischosen() { scanner menuinput = createnewscanner(); choice = menuinput.nextline(); /* code goes through array of valid input */ for(; useroption < validguesscomputernumberoptions().length; useroption++) checkifchoiceequalsvalidoption(); } private void checkifchoiceequalsvalidoption() { if(choice.tolowercase().equals(validguesscomputernumberoptions()[useroption])) { playgame(); } } private string[] validguesscomputernumberoptions() { string[] inputoptions = {"a", "b", "c", "d"}; // list of input options return inputoptions; } }
i want able create method asks user input each time not match string array found @ validguesscomputernumberoptions();
i have tried code continue array index out of bounds error.
not working code:
private void checkifguesscomputernumberischosen() { scanner menuinput = createnewscanner(); // createnewscanner defined method in code choice = menuinput.nextline(); for(; useroption < validguesscomputernumberoptions.length; useroption++) { checkifchoiceequalsvalidoption(); while(!choice.tolowercase().equals(validguesscomputernumberoptions()[useroption])) /* if not equal string */ { choice = menuinput.nextline(); } }
specifically, best way find whether string not equal element in array of valid inputs, prompt user enter input again. also, feedback structure , functionality of code appreciated. note valid input "a", "b" [...] example valid inputs, , not actual.
i recommend creating method use in while loop
:
public boolean checkinput(string input) { string[] inputoptions = {"a", "b", "c", "d"}; for(string : inputoptions) { if(input.equals(i)) { return true; } } return false; } while(!checkinput(choice)) { choice = menuinput.nextline(); } //after loop choice equal b c or d...
Comments
Post a Comment