Thursday, 19 September 2013

Detecting Numbers in a String Variable (In Java)

Detecting Numbers in a String Variable (In Java)

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. Level up, yo!\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 collection
variables value (1). Did I do something wrong or should I use a different
type of variable?

No comments:

Post a Comment