2017-12-05 4 views
-4

이것은 1000000 개의 요소가있는 텍스트 파일에서 8675309라는 숫자를 찾아야하는 숙제 문제 중 하나입니다. 이 기능을 사용하려면 선형 검색을 사용하는 방법에 대해 혼란스러워합니다. 또한 내 Java 폴더로 이동하는 텍스트 파일은 csc210hw5A-datafile이라고해야합니까?선형 검색 숙제

import java.util.Scanner; 
import java.util.NoSuchElementException; 

import java.io.FileInputStream; 
import java.io.FileNotFoundException; 

public class SKELcsc210hw5A { 

// linearSearch: return index of matching element. 
//    If not found, return -1. 
private static int linearSearch(int[] arr, int N, int query) { 
    int idx = -1; 
    for(int i = 0; i < N; i++){ 
       if(arr[i]==query);{ 
       //stuck here 
      } 

      } 
    return idx; 

} 

private static int[] loadFile(String fileName) { 
    int[] vals = null; 
    int sz = -1; 
    try { 
     Scanner sc = new Scanner(new FileInputStream(fileName)); 
     if(sc.hasNextInt()) 
      sz = sc.nextInt(); 
     if (sz < 0) { 
      System.out.println("File not the right format!"); 
      return vals; 
     } 
     vals = new int[sz]; 
     for(int ii = 0; ii < sz; ii++) { 
      vals[ii] = sc.nextInt(); 
     } 
    } catch (FileNotFoundException excptn) { 
     System.out.println(excptn.getMessage()); 
    } catch (NoSuchElementException excptn) { 
     System.out.println("Unexpected end of file!"); 
     vals = null; 
    } 
    return vals; 
} 

public static void main (String[] args) { 
    String fName = "csc210hw5A-datafile.txt"; 
    if(args.length > 0) { 
     fName = args[0]; 
    } 
    int[] values; 

    System.out.println("Loading... " + fName); 
    if((values = loadFile(fName)) == null) { 
     System.out.println("Failed to read " + fName + ": Exiting."); 
     return; 
    } 
    System.out.println("Loaded " + fName + " successfully."); 

    int query = 8675309; 
    if(args.length > 1) { 
     query = Integer.parseInt(args[1]); 
    } 
    System.out.println("Query to search: " + query); 
    System.out.println("Total elements to search: " + values.length); 

    int idx = linearSearch(values, values.length, query); 

    if(idx != -1) 
     System.out.println("Query found on line " + (idx+1)); 
    else 
     System.out.println("Query not found"); 
    } 
} 

loadFile 이후의 모든 항목이 완료되었습니다.

+0

'if' 다음에';'가 있지만, 파일 이름을 바꾸는 방법에 대해 궁금한 점이 있습니다 만, 두 번째 생각에서';'는 강사의 함정이며, 파일 이름 질문은 강사가 코드를 읽는 것과 관련하여 변경 방법을 이해하는 것입니다. –

+0

선형 검색과 파일 판독기의 기본 사항을 읽어 보시기 바랍니다. –

답변

0

은에서 : http://www.geeksforgeeks.org/linear-search/

class LinearSearch { 
// This function returns index of element x in arr[] 
static int search(int arr[], int n, int x) { 
    for (int i = 0; i < n; i++) { 
     // Return the index of the element if the element is found 
     if (arr[i] == x) { return i; } 
    } 

    // return -1 if the element is not found 
    return -1; 
} 
} 

아이디어는 : 당신이 일을 찾을 때까지 당신의 배열을 검색합니다. 그렇게하면 즉시 그 자세를 되돌립니다. 찾지 못하면 -1을 반환합니다.

이 두 S.O. 페이지 및 내가 링크 한 페이지가 있습니다.

+0

네, 이것을 시도하고 효과가있었습니다. 정말 고맙습니다! – Thinking

0
private static int linearSearch(int[] arr, int N, int query) { 
    int idx = -1; 
    boolean isFound = false; 
    for(int i = 0; i < N && !isFound; i++) 
    { 
     if(arr[i]==query) 
     { 
      isFound = true; 
      idx = i 
     } 

    } 
    return idx; 
} 
+0

예, 텍스트 파일은 Java 코드 폴더와 동일한 디렉토리에 있어야합니다. 원하는 이름으로 텍스트 파일의 이름을 지정할 수 있습니다. 그것은 특별히 "csc210hw5A-datafile.txt"가 될 필요가 없습니다. –

+0

아마도 '휴식'을 원할 것입니다. 또한, 당신이 한 일을 설명하면 OP에 유용 할 것입니다. –

+0

감사합니다! 그러나 위에서 작성한 코드는 작동하지 않습니다. 구문에 오류가있는 경우 : Invert If – Thinking