Array.binarySearch返回错误的数据 [英] Array.binarySearch returning wrong data
问题描述
我想验证用户名和密码使用数组和array.BinarySearch功能。数组中的前两个用户名:布拉德利和约翰正在使用的功能0和1返回正确的位置,但是当我尝试验证数组吉姆和克拉克最后两个字符串的函数的binarySearch返回的用户名位于位置-2两次数组,这是造成验证失败英寸任何想法?
的String [] =名称{布拉德利,约翰,吉姆,克拉克};
的String [] =密码{密码,密码,测试,测试};
INT POS = Arrays.binarySearch(姓名,UNAME);
的System.out.println(发现你的数组:+ +的uname的位置:+ POS)
如果(POS> = 0)
{
的System.out.println(用于验证口令:+的uname);
如果(密码[POS] .equals(PWORD)及和放大器;!loggedOn [POS])
{
}
您名称
数组没有排序:
的String [] =名称{布拉德利,约翰,吉姆,克拉克};
这是<一个要求href=\"http://docs.oracle.com/javase/7/docs/api/java/util/Arrays.html#binarySearch%28java.lang.Object%5b%5d,%20java.lang.Object%29\"相对=nofollow> 的binarySearch()
(和的二进制搜索算法):
的范围必须升序排序
块引用>第一个排序它,它就会像一个魅力:
的String [] =名称{布拉德利,克拉克,吉姆,约翰};
I am trying to validate password and username using array and the array.BinarySearch function. The first two user names in the array: bradley and john are returning the correct position using the function 0 and 1. However when I try to validate the last two strings in the array jim and clarke, the binarySearch function returns the username is located at position -2 in the array both times which is causing validation to fail. Any ideas?
String[] names = {"bradley","john","jim","clarke"}; String[] passwords = {"password","password","test","test"}; int pos = Arrays.binarySearch(names, uname); System.out.println("Found you in array:" + uname + "here:" + pos); if(pos >= 0) { System.out.println("Validation password for:" + uname); if(passwords[pos].equals(pword) && !loggedOn[pos]) { }
解决方案Your
names
array is not sorted:String[] names = {"bradley","john","jim","clarke"};
which is a requirement of
binarySearch()
(and binary searching algorithm in general):The range must be sorted into ascending order
Sort it first and it'll work like a charm:
String[] names = {"bradley","clarke","jim","john"};
这篇关于Array.binarySearch返回错误的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!