Scanner.nextLine输入不能与String匹配

时间:2015-03-16 19:47:17

标签: java java.util.scanner

我在使用Scanner.nextline()时遇到了一些麻烦,看起来工作正常并且花花公子,直到我尝试将输入与相应的字符串进行比较。 我基本上想看看某些输入是否等于数组中的某些元素(团队)。这是我的代码和输出:

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();

}
}

输出:

'Team A' in teams: true
Team: 
Team A  //My Input

Not in array: Team A, length: 6
Team: 

显然输出的长度合适,当我在inArray方法中使用纯String“Team A”时它返回true,所以我不明白为什么输入不被解释为在数组中?

1 个答案:

答案 0 :(得分:1)

这是错误的if(array[i] == thing){,对字符串使用等于:if(array[i].equals(thing)){。熊猫,你应该真正了解其中的差异:)