java - 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!");
}
}
}
解决方案
正如@Eran 在评论中所说,问题出在你的字母表中'V','W','X'
。
你也不需要int bck = 0
,因为你可以让 while 循环像总是循环一样,直到你像这样停止程序while(true)
:
推荐阅读
- python - 如何确定提交是否进入稳定版本(TensorFlow)
- xslt - 使用 XSLT 从 JSON 输出中提取特定字段
- wordpress - Wordpress:获取帖子但不是完整的 WP_Post 对象
- powershell - 使用 Powershell 从日志文本中提取用户名
- python - 读取文件时允许月份格式变化
- python - Panda Dataframe:迭代列标题和相应的值
- python - 未检测到@cached_property doctest
- python - 如何用不同的哈希函数和冲突解决策略编写 Python 的 dict?
- python - 熊猫:用与索引值匹配的另一个数据框的列值(字符串)替换列中的索引值(int)
- sql - Bteq if then 条件