binarySearch使用数组时

时间:2015-07-27 00:45:38

标签: java arrays compiler-errors

我是java的新程序员,我正在尝试使用binarySearch在一个捕获3个州名的数组中查找特定的州名。在这种情况下,我选择了TEXAS。代码中的其他所有内容都一直到二进制搜索,我得到编译器错误“无法找到符号TEXAS”。有人能告诉我我做错了吗?

import java.util.Scanner;
import java.util.Arrays;

public class OrozcoBLE64 {
    private static Scanner input = new Scanner(System.in);

    public static void main(String[] args) {    
        String[] stateNameArray = new String[3];
        String[] stateNameArrayCopy = new String[stateNameArray.length];

        for (int counter = 0; counter < 3; counter++) {

            System.out.printf("Enter the name for state %d:\n ", counter + 1);
            stateNameArray[counter] = input.nextLine().toUpperCase();

            System.arraycopy(stateNameArray, 0, stateNameArrayCopy, 0, stateNameArray.length);
        } // end of for loop

        boolean copyEquals = Arrays.equals(stateNameArray, stateNameArrayCopy);
        System.out.printf("stateNameArray %s stateNameArrayCopy\n\n",
                (copyEquals ? "equals" : "does not equal")); //displays if arrays are equal after copy.

        Arrays.sort(stateNameArray);
        System.out.printf("The statesNameArray has been sorted\n");

        boolean sortEquals = Arrays.equals(stateNameArray, stateNameArrayCopy);
        System.out.printf("stateNameArray %s stateNameArrayCopy\n\n",
                (sortEquals ? "equals" : "does not equal"));

        String state = Arrays.binarySearch(stateNameArray, TEXAS);

        if (state == TEXAS) {
            System.out.printf("Found TEXAS at element %d in statesNameArray\n", state);
        }
    } // end of main method
} // end of class

1 个答案:

答案 0 :(得分:2)

您应该使用字符串API equals()而不是&#39; ==&#39;用于字符串比较。