BabyC0d3eR BabyC0d3eR - 6 months ago 15
Java Question

How to validate string from user input to pre defined name

Hello all I am trying to write a loop in my code that would prompt user if they enter something other than what I have predefined. I am somewhat familiar with this done to user input that is not specific word or int but not sure when user has three choices to choose from.

System.out.print("Please enter your class. (Mage, Archer, Warrior)\n");
String nameofClass = myinput.next().toLowerCase();
gameplayer.setclassName(nameofClass);


So if user inputs "done"

then I will prompt the message saying I'm sorry, what was that?
this messages continues till user enters one of the option

Here I am posting entire code

import java.util.Arrays;
import java.util.List;
import java.util.Scanner;

// this class will instantiates player object
public class Adventure {

public static void main(String[] args) {
// main method

System.out.println("Hello and welcome to my text adventure! ");
List<String> names = Arrays.asList("mage","archer","warrior");
Scanner myinput = new Scanner(System.in);
Player gameplayer = new Player(); // create a player object and assign it to gameplayer
System.out.print("Please enter your name.\n");
String nameofPlayer = myinput.nextLine();
gameplayer.setPlayer(nameofPlayer);

System.out.print("Please enter your class. (Mage, Archer, Warrior)\n");
String userinput;
while (myinput.hasNext()) {
userinput = myinput.nextLine();
String nameofClass = userinput.toLowerCase();
if (!names.contains(nameofClass)) {
System.out.println("I'm sorry, what was that?");

} else {
gameplayer.setclassName(nameofClass);
System.out.println("Hello " + gameplayer.getPlayer() + " the "+ gameplayer.getClassName()+ ". What health do you have?");
return;
}
}
int numberofHealth = myinput.nextInt();
gameplayer.setHealth(numberofHealth);

System.out.println("Very good. Now let's get started on your adventure.");

}
}
}

Answer
try this out with List<String> for you names and the java contains().

List<String> names = Arrays.asList("mage","archer","warrior");
    Scanner scanner = new Scanner(System.in);
    String myinput;
    while (scanner.hasNext()) {
        myinput = scanner.nextLine();
        String nameofClass = myinput.toLowerCase();
        if (!names.contains(nameofClass)) {
            System.out.println("I'm sorry, what was that?");

        } else {
            gameplayer.setclassName(nameofClass);
            return;
        }

    }