首页 > 解决方案 > Java binarySearch 找不到所有字符

问题描述

大家好,我创建了一个排序的数组列表,但是当我搜索字符 W 时,它没有找到。可能是什么问题。

public class BinarySearch {

    public static void main(String[] args) {

        char[] nam = {'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','X','W','Y','Z'};

        char code;
        int pos;
        int bck = 0;
        while (bck == 0) {            
        
        Scanner sc= new Scanner(System.in);
        System.out.print("Enter the Alphabet: ");
        String str = sc.next();
        code = str.toUpperCase().charAt(0);
        pos = Arrays.binarySearch(nam, code);
        if (pos >= 0) {
            System.out.println("Alphabet "+code+" is at position "+ ++pos);
        }else{
            System.out.println("Character not found!");
        }
    }
}

标签: javaarrays

解决方案


正如@Eran 在评论中所说,问题出在你的字母表中'V','W','X'

你也不需要int bck = 0,因为你可以让 while 循环像总是循环一样,直到你像这样停止程序while(true)


推荐阅读