Why does this code taking input of string and outputting an int not work? Java
if-statement, int, java, string
Solution
For testing Object (non-primitive type) equality, use `Object.equals()`.
if(input.equals("1")) {
return 1;
}
The `==` operator checks whether the references to the objects are equal. A test for reference equality is done within the `String.equals() method`, among other checks. Below is the Java source for the `String.equals()` method:
public boolean equals(Object anObject) {
if (this == anObject) { // Reference equality
return true;
}
if (anObject instanceof String) {
String anotherString = (String)anObject;
int n = count;
if (n == anotherString.count) { // Are the strings the same size?
char v1[] = value;
char v2[] = anotherString.value;
int i = offset;
int j = anotherString.offset;
while (n-- != 0) {
if (v1[i++] != v2[j++]) // Compare each character
return false;
}
return true;
}
}
return false;
}
Problem
Possible Duplicate: Java String.equals versus == I thought this would be a neat way of structuring a picker method but the output is not going to the first two if statements and only outputs the last ``` public int myPickerMethod(){ System.out.println("please select from the options "); System.out.println("please select 1 for option 1 "); System.out.println("please select 2 please select 2 for option 2"); String input = keyboard.readLine(); System.out.println("input = " + input); if(input=="1"){ return 1; } else if(input=="2"){ return 2; } else{ return 42; } } ``` Here is my result from the terminal: ``` please select from the options please select 1 for option 1 please select 2 please select 2 for option 2 1 input = 1 response = 42 ``` Same goes if I put 2 in. the "response" print statement is the output from the method from a print statement in the main class. I have not tried this way before but I figured it should work. I don't really get why it isn't. Anyone able to clear this up? Thanks