Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

While Not Equal to String

Tags:

java

I'm making a text based RPG game and I am creating a chooseClass method. See the code:

public static void classChoice(){
    String cont =null;
    String[] classes = {"rogue", "wizard", "knight", "archer"};
    Scanner input = new Scanner(System.in);
    do{
        System.out.println("Choose your class (Rogue, Wizard, Knight, Archer): ");
        cont = input.next();
        if (cont.equalsIgnoreCase("rogue")){
            System.out.println("You have chosen the Rogue!");
        } else if (cont.equalsIgnoreCase("wizard")) {
            System.out.println("You have chosen the Wizard!");
        } else if (cont.equalsIgnoreCase("knight")) {
            System.out.println("You have chosen the Knight!");
        } else if (cont.equalsIgnoreCase("archer")) {
            System.out.println("You have chosen the Archer!");
        } else {
            System.out.println("Choose a valid class!");
        } 
    } while(!cont.equals(classes));
}

So I made a string array for all of the classes, and I thought that I could make the user input "cont" and say that while it is not equal to any of the "classes" array values, then print the message "Choose a valid class!". It isn't working, any ideas?

like image 381
Adam Basham Avatar asked Feb 18 '26 14:02

Adam Basham


1 Answers

cont.equals(classes) doesn't test whether cont is in classes. It tests whether cont is equal to classes. Since cont is a String and classes is an array of Strings, this will never be true.

I recommend using Arrays.asList to make a list of classes. Then, you can test whether the list contains cont:

classes = Arrays.asList("rogue", "wizard", "knight", "archer");

... while (!classes.contains(cont));
like image 160
user2357112 supports Monica Avatar answered Feb 21 '26 04:02

user2357112 supports Monica



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!