2014-01-29 73 views
0

我在編寫一個程序,要求用戶輸入用戶想要創建的數組的大小,然後要求用戶使用元素填充數組,那麼它應該顯示帶有其元素的數組,並要求用戶搜索整數。它應該進行線性和二進制搜索,同時顯示需要確定的元素數量。到目前爲止,我得到的唯一結果是該元素尚未找到。如果你能看看我的代碼,看看問題是什麼,因爲我已經嘗試了幾個小時,並且改變了我能想到的一切。任何幫助將不勝感激。在java中使用線性和二進制搜索的用戶輸入

import java.util.Scanner; 

public class Searching 
{ 
public static int[] anArray = new int[100]; 

private int numberOfElements; 

public int arraySize = numberOfElements; 

public String linearSearch(int value) 
{ 

    int count = 0; 

    boolean valueInArray = false; 

    String indexOfValue = ""; 

    System.out.print("The Value was Found in: "); 

    for(int i = 0; i < arraySize; i++) 
    { 
     if(anArray[i] == value) 
     { 
      valueInArray = true; 

      System.out.print(i + " "); 

      indexOfValue += i + " "; 

     } 
     count ++; 
    } 
    if(!valueInArray) 
    { 
     indexOfValue = " None found"; 

     System.out.print(indexOfValue); 
    } 
    System.out.println("\nIt took " + count + " probes with a linear search to find"); 

    return indexOfValue; 

} 

public void binarySearch(int value) 
{ 

    int min = 0; 
    int max = arraySize - 1; 
    int count = 0; 

    while(min <= max) 
    { 

     int mid = (max + min)/2; 

     if(anArray[mid] < value) min = mid + 1; 

     else if(anArray[mid] > value) max = mid - 1; 

     else 
     { 

      System.out.println("\nFound a Match for " + value + " at Index " + mid); 

      min = max + 1; 
     } 
     count ++; 
    } 
    System.out.println("It took " + count + " probes with a binary search to find"); 
} 

public static void main(String[] args) 
{ 
    @SuppressWarnings("resource") 
    Scanner scan = new Scanner(System.in); 

    System.out.println("Input the number of elements in your Array"); 
    int numberOfElements = scan.nextInt(); 

    if(numberOfElements <= 0) 
    { 
     System.exit(0); 
    } 

    int[] anArray = new int[numberOfElements]; 

    System.out.println("\nEnter " + numberOfElements + " Integers"); 
    for(int i = 0; i < anArray.length; i ++) 
    { 
     System.out.println("Int # " + (i + 1) + ": "); 
     anArray[i] = scan.nextInt(); 
    } 

    System.out.println("\nThe integers you entered are: "); 
    for(int i = 0; i < anArray.length; i ++)  // for loop used to print out each element on a different line 
    { 
     System.out.println(anArray[i]); 
    } 

    System.out.println("Which element would you like to find?"); 
    int value = scan.nextInt(); 

    Wee3Q2JOSHBALBOA newArray = new Wee3Q2JOSHBALBOA(); 

    newArray.linearSearch(3); 

    newArray.binarySearch(value); 

} 
} 

回答

0

嗯,我不知道你使用的是陣列的正確途徑,你看到一個陣列是一組大小和我不認爲你可以展開像他們這樣,你正在做的...

相反嘗試將數組的大小設置爲特定的長度。 或使用矢量