2014-10-31 3 views
1

각 줄에 숫자가있는 텍스트 파일이 있습니다.텍스트 파일에서 데이터 읽기 및 개체에 저장

0 
55 
3 
15 
63 
8 
0 
-8 
9 
89 
504 
32 

I이 세 매개 변수를 받아들이 Car :

  • 판독 개시 주행
  • 리터

텍스트의 첫 번째 행을 판독 최종 주행 파일은 시작 주행 거리계에 해당합니다.
두 번째가 마지막 읽기입니다.
세 번째는 리터입니다.
네 번째는 두 번째 Car 독서를 시작 주행 등 내가 텍스트 파일을 읽어 객체를 생성 할 필요가

, 그리고 차에이 매개 변수입니다.

car3 (0, -8, 9)의 경우 음수가 있으므로 전체 집합이 무시되고 (89, 504, 32)car3이됩니다.

나는 Anubian Noob's answer을 참조했습니다. 이것은 내 코드는 지금까지 있습니다 :

라인 나는 다음과 같은 오류 얻을 int liter = Integer.parseInt(inputFile.readLine());
final String INPUT_FILE = "data.txt"; 
final String OUTPUT_FILE = "report.txt"; 

BufferedReader inputFile = new BufferedReader (new FileReader (INPUT_FILE)); 
BufferedWriter outputFile = new BufferedWriter (new FileWriter (OUTPUT_FILE)); 
LineNumberReader lineNumber = new LineNumberReader (new FileReader (INPUT_FILE)); 
lineNumber.skip(Long.MAX_VALUE); 
int length = lineNumber.getLineNumber(); 
lineNumber.close(); 


String line = inputFile.readLine(); 

Car[] car = new Car[length/3]; 

while (line != null) 
{ 
    for (int i = 0; i < length/3; i += 3) 
    { 
     int startReading = Integer.parseInt(inputFile.readLine()); 
     int endReading = Integer.parseInt(inputFile.readLine()); 
     int liter = Integer.parseInt(inputFile.readLine()); 
     car[i] = new Car (startKm, endKm, litre); 
    } 
} 
inputFile.close(); 
outputFile.close(); 

:

java.lang.NumberFormatException: null 
null (in java.lang.Integer) 

가 어떻게 각각의 객체로 정보의 세 가지를 저장 할를?

* 참고 : 텍스트 파일에 설정된 양의 줄이 없으므로 배열을 사용해야합니다.

+1

즉, 파일의 끝에 도달했음을 의미합니다. 왜 같은 파일에 대해 두 개의 Reader 인스턴스가 있습니까? ['Files.readAllLines'] (http://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html#readAllLines (java.nio.file.Path, % 20java) .nio.charset.Charset)). –

+0

정수 변환을 수행하기 전에 현재 행의 로그를 인쇄하여 실패 할 경우 정확히 어떤 행을 알도록하십시오. 이것과 별개로, Boris와 같은 코멘트 : 당신은 당신의 독자로서 lineNumber만을 유지하는 것이 어떻습니까? – gdupont

+0

나는 BufferedReader와 LineNumberReader가 달랐다 고 생각했다. 'LineNumberReader' 만 남겨두고'inputFile'을'lineNumber'로 바꾸면'String line = inputFile.readLine(); '에서 에러가 발생합니다 java.io.IOException : Steam close (in java.io. BufferedReader' – user3479783

답변

2

파일의 첫 번째 줄을 읽고 사용하고 있지 않기 때문입니다. 파일의 두 번째 줄부터 시작하여 첫 번째 차량의 startReading에 할당합니다. 따라서 파일에 충분한 줄이 없을 것입니다. 줄 수와 파일 수를 계산하면 파일 한 줄을 너무 많이 읽게됩니다.

또한 루프를 실행해야합니다. i을 3으로 늘리십시오. 왜냐하면 이미 행 수를 3으로 나누었 기 때문입니다. 그리고 car 배열에 대한 인덱스로 i을 사용하고 있습니다.

변경 코드 :

lineNumber.close(); 

// REMOVE String line = inputFile.readLine(); 

Car[] car = new Car[length/3]; 

// REMOVE while (line != null) 
// REMOVE { 
for (int i = 0; i < length/3; i ++) // DON'T DO i += 3 because that will make you go beyond the bounds of the car array 
{ 
    int startReading = Integer.parseInt(inputFile.readLine()); 
    int endReading = Integer.parseInt(inputFile.readLine()); 
    int liter = Integer.parseInt(inputFile.readLine()); 
    car[i] = new Car (startKm, endKm, litre); 
} 
// REMOVE } 
+0

또는 단지'Files.readAllLines'을 사용하고 복잡성이 있다면 90 %를 없앱니다. –

1

코드의 문제는 아래의 중첩 루프입니다 :

당신이 line 변수를 초기화하는 inputFile의 첫 번째 라인을 읽고 때문에
String line = inputFile.readLine(); 
Car[] car = new Car[length/3]; 

while (line != null) 
{ 
    for (int i = 0; i < length/3; i += 3) 
    { 
     int startReading = Integer.parseInt(inputFile.readLine()); 
     int endReading = Integer.parseInt(inputFile.readLine()); 
     int liter = Integer.parseInt(inputFile.readLine()); 
     car[i] = new Car (startKm, endKm, litre); 
    } 
} 

, 모든 더 차 값이 읽어 오프 1 씩에 또한, line 변수를 다시 할당하지 않으므로 빈 파일을 읽지 않는 한 항상 null이 아니며 무한 루프가 생성됩니다.

외부 루프와 함께 line 변수 alltogether를 제거하면 이미 파일의 줄 수에 따라 조건이 있기 때문에 문제를 해결할 수 있습니다.

0

는 왜라는 클래스 차를 만들지 않습니다

public Class Car{ 
    private int starting_odometer; 
    private int final_odometer; 
    private int liters; 
    //Constructor 
    //Getters and setters 
} 

을 오른쪽 속성에 선을 파일을 읽고 설정 :

Car myCar = new Car(); 
BufferedReader br = new BufferedReader(new FileReader(file)); 
String line; 
int count=1; 
while ((line = br.readLine()) != null) { 
if(count<=3) 
{  
    if(count==1){ 
    myCar.setStarting_odometer(parseInt(line); 
    } 
    if(count==2){ 
    myCar.setFinal_odometer(parseInt(line); 
    } 
    if(count==3){ 
    myCar.setLiters(parseInt(line); 
    } 
    count++; 
} 
else {count=1;}  

} 
br.close(); 
관련 문제