2014-01-29 1 views
0

사용자가 만들려는 배열의 크기를 입력하도록 요청하는 프로그램을 작성한 다음 사용자에게 배열로 요소를 채우라고 요청합니다. 요소가있는 배열을 표시하고 사용자에게 정수 검색을 수행하도록 요청해야합니다. 선형 및 2 진 탐색을 수행하면서 요소가 배열에 있는지 확인하는 데 걸린 프로브 수를 표시해야합니다. 지금까지 내가 얻은 유일한 결과는 요소가 발견되지 않았다는 것입니다. 내가 몇 시간 동안 노력했기 때문에 내가 생각할 수있는 모든 것을 바꿨기 때문에 내 코드를보고 문제가 무엇인지 알 수 있다면. 어떤 도움이라도 대단히 감사하겠습니다. ... 대신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

흠, 당신은 볼 배열은 집합 크기이며, 나는 당신이 그들이 방법을 당신이하고있는 것처럼 확장 할 수 있습니다 같아요 배열의 크기를 특정 길이로 설정하십시오. 또는 벡터 사용

관련 문제