이것은 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 이후의 모든 항목이 완료되었습니다.
'if' 다음에';'가 있지만, 파일 이름을 바꾸는 방법에 대해 궁금한 점이 있습니다 만, 두 번째 생각에서';'는 강사의 함정이며, 파일 이름 질문은 강사가 코드를 읽는 것과 관련하여 변경 방법을 이해하는 것입니다. –
선형 검색과 파일 판독기의 기본 사항을 읽어 보시기 바랍니다. –