日期:2014-05-20  浏览次数:20757 次

大家看看我到底是那错了,你能HOLD住吗
import java.util.Arrays;
public class Keyword
{
  public static void main(String args[])
 {

 String Keywords[]= 

{"abstract","assert","break","byte","case","catch","char","class","continue","default","do"
 };
 Arrays.sort(Keywords);
 System.out.println(Keywords.toString());
 String key="youcan";
Arrays.binarySearch(key);
 }
}
 我就是将java中一些关键字保存在一个字符串数组中,对其按升序排序,在采用顺序或二分法查找,判断一个字符串是否是java关键字。

------解决方案--------------------
Java code

public class Keyword {
    public static void main(String args[]) {

    String Keywords[] =

    { "abstract", "assert", "break", "byte", "case", "catch", "char",
        "class", "continue", "default", "do" };
    Arrays.sort(Keywords);    
    System.out.println(Arrays.toString(Keywords));    
    String key = "youcan";
        int result = binarySearch(Keywords ,key);
    if(result == -1)System.out.println("不存在");
    else System.out.println("在第" + result +"个位置上");
    }   
    
    /**
     * 在字符串数组中(已经按字典顺序升序排序),查找指定的字符串
     * 如果存在,返回数组下标,否则返回-1
     * @param keywords
     * @param key
     * @return
     */
    public static int binarySearch(String keywords[] , String key){
    if(keywords == null || key == null) return -1;
    int left = 0; 
    int right = keywords.length -1;    
    while(left<=right){
    int mid =(left + right)/2 ;
    String temp =keywords[mid];
    if(temp.equals(key)) return mid;
    if(temp.compareTo(key) < 0) left = mid + 1;
    else right = mid-1;
    }
    return -1;    
    }    
}

------解决方案--------------------
int result = Arrays.binarySearch(Keywords ,key);
------解决方案--------------------
Arrays.binarySearch()使用错误
------解决方案--------------------
同意一楼的方法。
输出数组需要循环遍历数组,搜索数组中的元素,返回值为int型,根据不同的key,获得不同的结果!
int result = Arrays.binarySearch(Keywords ,key);