2015-12-14 66 views
-1

我已創建此代碼,它是一個圖表位置。它應該允許用戶輸入數組中已經設置的名稱和藝術家的位置會同時輸入輸出沒有「結束」線性排序搜索

public static void main(String[] args) { 
    Scanner kybd = new Scanner (System.in); 
    String names = null; 

    String [] Artists = new String []; 
    String [] Artists = new String []{"Fetty Wap", "Drake", "Miley Cyrus" 
    ,"Kanye West","Chris Browna","Tinie Tempah","Robin Thicke","The Weeknd" 
    ,"Jay Z","The Wanted"}; 

    do{ 
     System.out.println("Please enter name "); 
     names = kybd.next(); 
    } while (!names.equalsIgnoreCase("end")) ; 
} 

public static int linearSorted(int[] array, int item) 
{ 
    int index = 0; 
    while (index < array.length && 
    array[index] != item && 
    array[index] < item) 
    { 
     index++; 
    } 

    if (index == array.length || 
    array[index] > item) 
    { 
     index = -1; 
    } 
    return index; 
} 
} 

的問題,我是來的是,它不顯示因爲它是在數組中排序

+3

你一定要明白你的陣中有一半是空的,因爲排行榜位置你只是不停地在'Artists [1]'中插入不同的值? – azurefrog

+1

以'String [] s = new String [] {「foo」,「bar」,「baz」};'創建假數據更爲簡潔,因此數組總是緊湊且大小正確。 – azurefrog

+1

我不明白你要在這裏做什麼。你說你試圖'允許用戶輸入一個已經在數組中設置的名字,而藝術家的位置將會在輸入不是「結束」的情況下輸出,但是你不會爲這個位置輸入一個輸入,你也不會調用你的'linearSorted'方法。請在你的問題中提供更多細節。 – azurefrog

回答

0

如果所有你需要做的是找到名稱指數的線性搜索,然後這應該工作

public static void main(String[] args) { 
    Scanner sc = new Scanner(System.in); 
    String name = null; 
    String [] Artists = new String []{"Fetty Wap", "Drake", "Miley Cyrus" 
      ,"Kanye West","Chris Browna","Tinie Tempah","Robin Thicke","The Weekend" 
      ,"Jay Z","The Wanted"}; 

      do{ 
       System.out.print("Please enter name: "); 
       name = sc.nextLine(); 
       System.out.println(linearSearch(Artists, name)); 
      } while (!name.equalsIgnoreCase("end")) ; 

} 

public static int linearSearch(String[] arr, String name){ 
    for(int i = 0; i < arr.length; i++){ 
     if(arr[i].equals(name)){ 
      return i; 
     } 
    } 
    return -1; 
}