2014-01-29 2 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

хмм Я не уверен, что вы используете массиву правильный путь, вы видите массив представляет собой набор размера, и я не думаю, что вы можете расширить, как они, как вы делаете ...

Вместо попробуйте установить размер массива на определенную длину. или использовать векторы

 Смежные вопросы

  • Нет связанных вопросов^_^