2014-04-24 2 views
0

나는 전화 번호부 프로젝트를하고 있어요에게 독서하지 않는 것 그리고 우리는스캐너 파일

내가로부터 데이터를로드하기 위해 스캐너를 사용하고 디렉토리 파일 telnos.txt에서 읽을 필요 이전 질문에서 loadData 메소드를 사용하여 telnos.txt 파일을 작성했습니다. 여기서 StackOverflow에 대해 질문했습니다.

사용자가 항상 찾을 수 없음을 발견 했으므로 몇 가지 System.out.printlns를 메소드에 추가하여 무슨 일이 일어나는지 볼 수있게했습니다. 스캐너가 파일에서 아무 것도 읽지 않는 것 같습니다. 이상하게도, 첫 번째 줄을 읽어야하는 파일 이름을 출력하고 있기 때문에 여기서 아주 간단한 것을 놓친 것 같아요.

콘솔

run: 
    telnos.txt 
    null 
    loadData tested successfully 
    Please enter a name to look up: John 
    -1 
    Not found 
    BUILD SUCCESSFUL (total time: 6 seconds) 

ArrayPhoneDirectory.java

import java.util.*; 
import java.io.*; 

public class ArrayPhoneDirectory implements PhoneDirectory { 
    private static final int INIT_CAPACITY = 100; 
    private int capacity = INIT_CAPACITY; 

    // holds telno of directory entries 

    private int size = 0; 

    // Array to contain directory entries 

    private DirectoryEntry[] theDirectory = new DirectoryEntry[capacity]; 

    // Holds name of data file 

    private final String sourceName = "telnos.txt"; 
    File telnos = new File(sourceName); 

    // Flag to indicate whether directory was modified since it was last loaded or saved 

    private boolean modified = false; 

    // add method stubs as specified in interface to compile 

    public void loadData(String sourceName) { 
     Scanner read = new Scanner("telnos.txt").useDelimiter("\\Z"); 
     int i = 1; 
     String name = null; 
     String telno = null; 
     while (read.hasNextLine()) { 
      if (i % 2 != 0) 
       name = read.nextLine(); 
      else 
       telno = read.nextLine(); 
      add(name, telno); 
      i++; 
     } 
    } 

    public String lookUpEntry(String name) { 
     int i = find(name); 
     String a = null; 
     if (i >= 0) { 
      a = name + (" is at position " + i + " in the directory"); 
     } else { 
      a = ("Not found"); 
     } 
     return a; 
    } 

    public String addChangeEntry(String name, String telno) { 
     for (DirectoryEntry i : theDirectory) { 
      if (i.getName().equals(name)) { 
       i.setNumber(telno); 
      } else { 
       add(name, telno); 
      } 
     } 
     return null; 
    } 

    public String removeEntry(String name) { 
     for (DirectoryEntry i : theDirectory) { 
      if (i.getName().equals(name)) { 
       i.setName(null); 
       i.setNumber(null); 
      } 

     } 
     return null; 
    } 

    public void save() { 
     PrintWriter writer = null; 
     // writer = new PrintWriter(FileWriter(sourceName)); 

    } 

    public String format() { 
     String a; 
     a = null; 
     for (DirectoryEntry i : theDirectory) { 
      String b; 
      b = i.getName() + "/n"; 
      String c; 
      c = i.getNumber() + "/n"; 
      a = a + b + c; 

     } 
     return a; 
    } 


    // add private methods 


    // Adds a new entry with the given name and telno to the array of 
    // directory entries 
    private void add(String name, String telno) { 
     System.out.println(name); 
     System.out.println(telno); 
     theDirectory[size] = new DirectoryEntry(name, telno); 
     size = size + 1; 
    } 


    // Searches the array of directory entries for a specific name 
    private int find(String name) { 
     int result = -1; 
     for (int count = 0; count < size; count++) { 

      if (theDirectory[count].getName().equals(name)) { 
       result = count; 
      } 
      System.out.println(result); 
     } 
     return result; 
    } 

    // Creates a new array of directory entries with twice the capacity 
    // of the previous one 
    private void reallocate() { 
     capacity = capacity * 2; 
     DirectoryEntry[] newDirectory = new DirectoryEntry[capacity]; 
     System.arraycopy(theDirectory, 0, newDirectory, 
       0, theDirectory.length); 

     theDirectory = newDirectory; 
    } 


} 

ArrayPhoneDirectoryTester.java

import java.util.Scanner; 

public class ArrayPhoneDirectoryTester { 
    public static void main(String[] args) { 
     //create a new ArrayPhoneDirectory 
     PhoneDirectory newTest = new ArrayPhoneDirectory(); 

     newTest.loadData("telnos.txt"); 
     System.out.println("loadData tested successfully"); 
     System.out.print("Please enter a name to look up: "); 
     Scanner in = new Scanner(System.in); 
     String name = in.next(); 
     String entryNo = newTest.lookUpEntry(name); 
     System.out.println(entryNo); 


    } 

} 

telnos.txt

John 
123 
Bill 
23 
Hello 
23455 
Frank 
12345 
Dkddd 
31231 
+0

어디 다음과 같이 당신은 또한 함수에서 FileNotFoundException이를 잡을 필요가

String workingDir = System.getProperty("user.dir"); System.out.println("Current working directory : " + workingDir); 

파일이 있습니까? – manan

+0

이 문제를 축소하여 공유 할 수 있습니까? 종종 문제를 줄이면 스스로 해결할 수 있습니다! – pamphlet

+0

스캐너 사용 시도 = 새로운 스캐너 (새 파일 ("telnos.txt")); – manan

답변

0

필요

new Scanner("telnos.txt") 

:

Scanner read = new Scanner("telnos.txt"); 

은 'telnos.txt을'파일을로드하지 않을 . 대신 "telnos.txt"문자열을 검사하는 Scanner 객체를 만들 것입니다.

Scanner read = new Scanner(new File("telnos.txt")); 

또는 File 객체를 생성하고 스캐너 생성자에 해당 경로를 통과 : 스캐너를 만들려면 은 하나에 당신이 파일을 검사하는 것으로 알고 있습니다.

"파일을 찾을 수 없음"오류가 발생하는 경우 현재 작업 디렉토리를 확인해야합니다. 다음 라인을 실행하고 당신이 바로 그 디렉토리에 실제로있는 경우있는 파일입니다 볼 수 있습니다 :

public void loadData(String sourceName) { 
     try { 
     Scanner read = new Scanner(new File("telnos.txt")).useDelimiter("\\Z"); 
     int i = 1; 
     String name = null; 
     String telno = null; 
     while (read.hasNextLine()) { 
      if (i % 2 != 0) 
       name = read.nextLine(); 
      else { 
       telno = read.nextLine(); 
       add(name, telno); 
      } 
      i++; 
     } 
     }catch(FileNotFoundException ex) { 
     System.out.println("File not found:"+ex.getMessage); 
     } 
    } 
+0

고마워, 지금 그 일을하고있어, 파일을 찾을 수없는 예외를 준다. – Sam

+0

현재 작업 디렉토리. 현재 작업 디렉토리를 확인하는 단계로 내 답변을 편집했습니다. 다른 디렉토리라면 파일 경로를 수정하는 방법을 알게 될 것입니다. – user2881767

+0

@Sam 또한 코드에서 추가 (name, telno)를 else 블록으로 이동해야합니다. 그렇지 않으면 읽은 이름과 telno가 일치하지 않게됩니다. – user2881767