2014-03-29 7 views
0

내가이 텍스트 파일에서 읽은 다음 내 배열에에 뭐죠 추가하려고이 방법을 가지고, 내 방법은 괜찮을 것 같다, 하지만 내가 내 프로그램을 받고있을 때 null 화면에 여기 내 코드입니다 도와주세요.자바 텍스트 파일에서 읽기 (문자열과 정수)

File text = new File("C:\\Users\\Stephen\\Desktop\\CA2\\src\\Management_System_Package\\GAMES.txt"); 
    Scanner scnr = new Scanner(text); 

    String GameLine; 
    GameLine = scnr.nextLine(); 

    while (scnr.hasNextLine()) { 

     Management_System Game = new Management_System("", "", 0, 0, 0); 

     int Comma1 = GameLine.indexOf(", "); 
     String Title = GameLine.substring(0, Comma1).trim(); 
     Game.setTitle(Title); 

     System.out.print(Title); 

     int Comma2 = GameLine.indexOf(", ", Comma1 + 1); 
     String Genre = GameLine.substring(Comma1 + 1, Comma2); 
     Game.setGenre(Genre); 

     int Comma3 = GameLine.indexOf(", ", Comma2 + 1); 
     String ID = GameLine.substring(Comma2 + 1, Comma3); 
     Game.setID(Double.parseDouble(ID)); 

     int Comma4 = GameLine.indexOf(", ", Comma3 + 1); 
     String Rating = GameLine.substring(Comma3 + 1, Comma4); 
     Game.setRating(Integer.parseInt(Rating)); 

     String Quantity = GameLine.substring(Comma4 + 1).trim(); 
     Game.setQuantity(Integer.parseInt(Quantity)); 

     add(Game); 

     GameLine = in.nextLine(); 
+0

이, 내가 텍스트 파일 – StephenJpH

+0

자객 Cread, 액션, 1.0, 4, 5에서 읽으려고하고있는 무슨 -1 도움을 기꺼이 도움 – StephenJpH

답변

1

코드에 루프를 읽는 버그가 있고 파일의 마지막 줄을 항상 건너 뛸 수 있기 때문입니다. 파일에 한 줄만있는 경우 scnr.hasNextLine()false이고 while 루프는 실행되지 않습니다.

그리고 나는 split()이 원하는 문자열과 정수를 얻는 더 좋은 방법이라고 생각합니다. 이 같은 코드 :

String GameLine; 

while (scnr.hasNextLine()) { 
    GameLine = scnr.nextLine(); 
    Management_System Game = new Management_System("", "", 0, 0, 0); 
    String[] tags = GameLine.split(","); 

    Game.setTitle(tags[0]); 

    Game.setGenre(tags[1]); 

    Game.setID(Double.parseDouble(tags[2])); 

    Game.setRating(Integer.parseInt(tags[3])); 

    Game.setQuantity(Integer.parseInt(tags[4])); 

    add(Game); 
} 
+0

감사합니다 :) 나는 'split()'대신'indexOf()'를 사용할 것을 제안한다. – StephenJpH

+0

@StephenJpH에 대한 – locoyou

+0

네, 그렇게 할 것입니다. – StephenJpH