2017-03-10 2 views
0

파일을 읽고 각 행을 파일에서 OS_Process 객체의 매개 변수로 설정하려고 시도하고 있습니다. 그런 다음 해당 프로세스를 링크 목록 대기열에 배치합니다. 그러나, 나는 nullpointerexception을 계속 받고있다. 데이터 파일은 다음과 같습니다. 모든 새로운 공정 데이터는 새로운 라인에 있습니다.내 코드에서 널 포인터 예외를 수정하는 방법?

3 //counter 
1 3 6 //process 1 data 
3 2 6 //process 2 data 
4 3 7 //process 3 data 

는 그리고 이것은 당신이 String s = null;을 설정 한 다음이 StringTokenizer stz = new StringTokenizer(null); 같다 StringTokenizer stz = new StringTokenizer(s);를 호출하고 이것이 Nullpointer를 얻을 수 있기 때문에 NullpointerException이 내 코드

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

    public class OS_Scheduler 
    { 
    public static void main(String[] args) 
    { 
     Queue<OS_Process> jobs = new LinkedList<OS_Process>(); 

     try 
     { 
      System.out.print("Enter the file name: "); 
      Scanner file = new Scanner(System.in); 
      File filename = new File(file.nextLine()); 

      OS_Process proc = null; 
      String s = null; 
      int a = 0, p = 0, b = 0; 
      BufferedReader input = new BufferedReader(new FileReader(filename)); 
      StringTokenizer st = new StringTokenizer(s); 
      int count = Integer.parseInt(st.nextToken()); 
      while ((s = input.readLine()) != null) 
      { 
       st = new StringTokenizer(s); 
       a = Integer.parseInt(st.nextToken()); 
       p = Integer.parseInt(st.nextToken()); 
       b = Integer.parseInt(st.nextToken()); 
       proc = new OS_Process(a, p, b, 0); 
       jobs.add(proc); 
      } 
      input.close(); 
     } 
     catch (Exception ex) 
     { 
      ex.printStackTrace(); 
     } 

    } 
} 

답변

2

입니다.

그렇게 다음과 같이 코드를 업데이트 파일 의 마지막에 이르렀을 경우 파일의 모든 라인을 통해 while -loop 반복 중지 때문에 당신은 count 라인을 알 필요가 없습니다 :

String s = input.readLine();//read first line to get rid of it 
if(s == null){ 
    //File is empty -> abort 
    System.out.println("The file is empty"); 
    System.exit(0); 
} 
int a = 0, p = 0, b = 0; 
StringTokenizer st; 
while ((s = input.readLine()) != null) 
{...} 

하거나이 count 당신이 이런 식으로 작업을 수행 할 수 있습니다 사용하려는 경우 :

String s = input.readLine(); 
checkReadLineNotNull(s); 
int a = 0, p = 0, b = 0; 
StringTokenizer st = new StringTokenizer(s); 
int count = Integer.parseInt(st.nextToken()); 

for (int i = 0; i < count; i++) { 
    s = input.readLine(); 
    checkReadLineNotNull(s); 
    st = new StringTokenizer(s); 
    //... 
} 

//Checks if s != null otherwise kills the programm 
private static void checkReadLineNotNull(String s) { 
    if(s == null){ 
     //File is empty abort 
     System.out.println("The file is empty"); 
     System.exit(0); 
    } 
} 
+0

나는 그것을 해결하는 방법을 정확히 모르겠어요. 아무리해도 오류가 발생하여 초기화하지 않습니다. – TylerGBrooke

+0

정확히 어떤 오류가 있습니까? '파일 이름'이 있습니까? 'filename.exists() '를 통해 확인하십시오. –

+0

그래, 여전히 NullpointerException을 얻고 있습니다. 내가 null 대신 s를 바꿨지 만 이제는 nosuchelementException이 발생합니다. – TylerGBrooke

관련 문제