I am having some trouble with the Scanner.nextline(), it seems to work fine and dandy until I try to compare the input with the corresponding string. I basically want to see if some input is equal to some element in an array (teams). Here's my code and output:
package teams;
import java.util.Arrays;
import java.util.Scanner;
class TeamTable2 {
static String[] teams = new String[] {
"Team A", "Team B", "Team C",
"Team D", "Team E"
};
// inArray returns true if an specified string is "in" an specified array
static boolean inArray(String thing, String[] array){
boolean in = false;
for(int i = 0; i < array.length; i += 1){
if(array[i] == thing){
in = true;
}
}
return in;
}
static void inputInArray(){
Scanner userInput = new Scanner(System.in);
String inputTeam = null;
// The while loop continues if the input doesn't match any element
while(!inArray(inputTeam, teams)){
System.out.println("Team: ");
inputTeam = userInput.nextLine();
System.out.println("");
if(!inArray(inputTeam, teams)){
System.out.println("Not in array: " + inputTeam + ", length: " + inputTeam.length());
}
}
userInput.close();
}
public static void main(String args[]){
System.out.println("'Team A' in teams: " + inArray("Team A", teams));
inputInArray();
}
}
Output:
'Team A' in teams: true
Team:
Team A //My Input
Not in array: Team A, length: 6
Team:
So obviously the output has the right length and when I use the pure String "Team A" in the inArray method it returns true, so I don't understand why the input isn't interpreted as being in the array?