[英]Java binarySearch can't find all characters
大家好,我創建了一個排序的數組列表,但是當我搜索字符 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!");
}
}
}
正如@Eran 在評論中所說,問題出在你的字母表中,因為它應該是'V','W','X'
。
你也不需要int bck = 0
,因為你可以像總是循環一樣使 while 循環,直到你像這樣停止程序: while(true)
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.