0

So, normally for detecting user input, I use int and double variable types.

Example:

    Scanner in = new Scanner(System.in);
    int selection;
    System.out.println("Welcome to RPG! (prototype name)\nIn this game, you do stuff.\nChoose a class:\n1. Soldier\n2. Knight\n3. Paladin\n4. Heavy");
    selection = in.nextInt();   
    if(selection == 1){
        System.out.print("you are a soldier");
    }
    else{
        System.out.print(selection);
    }
}

This technique usually works fine for me, but I noticed that if the user inputs a letter into the int variable, the game will crash because integers can't store letters. (right?) So I tried using a String variable in its place, like this:

    Scanner in = new Scanner(System.in);
    String selection;
    System.out.println("Welcome to RPG! (prototype name)\nIn this game, you do stuff.\nChoose a class:\n1. Soldier\n2. Knight\n3. Paladin\n4. Heavy");
    selection = in.next();  
    if(selection == "1"){
        System.out.print("you are a soldier");
    }
    else{
        System.out.print(selection);
    }
}

This seemed to work at first, but as you can see, I have it set so that if the variable "selection" is equal to 1, that it will print "you are a soldier", yet this did not work, instead it printed out the "selection" variables value (1). Did I do something wrong or should I use a different type of variable?

yahooda
  • 11
  • 3

5 Answers5

1

you can use something la this :

 try{
           int type = Integer.parseInt(selection);
           switch(type){
           case 1:{
            //do soldier stuff   
           }
           case 2:{
            // do knight stuff   
           }
           default:{
               //do other stuff
           }
           }
       }catch(NumberFormatException exc ){
           System.out.println(selection + "is not a number, try again!!!");
       }
Eugen Halca
  • 1,775
  • 2
  • 13
  • 26
0
selection == "1"

Compare strings with String#equals.

"1".equals(selection)
Aurand
  • 5,487
  • 1
  • 25
  • 35
0

There are lots of ways to do this. A quick point I'd like to make is if you're comparing strings you should use:

var.equals("string");

Since you're only taking one character you could use a character in which case the correct syntax would be:

var == '1'

If you want to be fancy you can do a try catch around your read statement and just read in an string and parse it to an integer, but that is a bit more advanced.

0

change selection == "1" to "1".equals(selection)

wander
  • 937
  • 1
  • 7
  • 15
0

use .equals() for comparing the string "1" and selection and read this A simple explanation would be

x == y returns true only when both x and y refer to same object which is not in your case. equals check if contents are equal meaning if contents of memory location that x and y are referring to are equal or not.

Community
  • 1
  • 1
Prateek
  • 1,916
  • 1
  • 12
  • 22