2016-11-16 1 views
0

Netbeans에서 Java 프로젝트를 빌드 중입니다. 높은 (낮은) | (높음) 형식으로 높은 온도와 낮은 온도를 포함하는 데이터 파일 (temperature.txt)이 있습니다. 파일을 2 차원 배열로로드 한 다음 화면에 인쇄해야합니다. 하지만 자바 프로젝트를 실행할 때이 오류를 발견하고 완전히 잃어 버렸습니다. 하지만이 문제를 해결하는 방법을 모르겠습니다."main"스레드의 예외 java.lang.ArrayIndexOutOfBoundsException : 1

Temperature.text :

+-------------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+ 
| Day   | 1  | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 
+-------------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+ 
| Temperature | 30|32 | 29|30 | 25|28 | 25|29 | 27|31 | 28|32 | 26|30 | 24|32 | 24|41 | 27|32 | 
+-------------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+ 

출력 : 여기에

Analysis report of the temperature reading for the past 10 days 

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1 
    at Lab4Ex2.main(Lab4Ex2.java:48) 
C:\Users\User\AppData\Local\NetBeans\Cache\8.2\executor-snippets\run.xml:53: Java returned: 1 
BUILD FAILED (total time: 0 seconds) 

내 코드입니다 : 당신은 이미이 요청했는지 모르겠어요

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

public class Exercise { 

    public static void main(String[] args) { 

     StringTokenizer tokenizer; 
     String line; 
     String file="temperature.txt"; 
     int[][] temp=new int[10][2]; 
     int sumHigh, sumLow; 
     FileReader fr=null; 
     BufferedReader br=null; 

     try 
     { 
      fr=new FileReader(file); 
      br=new BufferedReader(fr); 

      line=br.readLine(); 
      System.out.println("Analysis report of the temperature reading for the past 10 days " + line); 

      String [] content=line.split("|"); 

      for(int row=0; row<=content.length; row++) 
      { 
       //I am trying to parse the two token into integer.. 

       if(row != 0) 
       { 
        try 
        { 
         //Parse first token into integer and store in current row column 0 
         if(row % 2 != 0) 
         { 
          sumLow = Integer.parseInt(content[row]); 
          temp[row][0]=Integer.parseInt(content[row]); <---Line 48 

         } 
         //Parse second token into integer and store in current row column 0 
         else if (row % 2 == 0) 
         { 
          sumHigh = Integer.parseInt(content[row]); 
          temp[row][1]=Integer.parseInt(content[row]); 
         } 
        } 
        catch(NumberFormatException e) 
        { 
         System.out.println("The code throws an exception"); 
        } 
       } 
       System.out.println(); 

      } 
      br.close(); 
     } 

     catch(FileNotFoundException e) 
     { 
      System.out.println("The file " + file + " was not found"); 
     } 
     catch(IOException e) 
     { 
      System.out.println("Reading error"); 
     } 
     catch(NumberFormatException e) 
     { 
      System.out.println("Parsing error"); 
     } 
     finally 
     { 
      if(fr != null) 
      { 
       try 
       { 
        fr.close(); 
       } 
       catch(IOException e) 
       { 
        System.out.println("Reading error"); 
       } 
      } 
     } 


    } 

} 
+0

어떤 라인이 48입니까? – bradimus

+0

'split()'이 * regex *를 사용한다는 것을 알아야합니다. 따라서,'| '는 "이쪽 또는 그쪽"인 구분자를 찾도록 지시하는 특수 문자입니다.이 경우에는 "아무것도 아니거나 아무것도 없습니다". 이것은 당신이 의도 한 것이 아닙니다. 대신에'\\ |'를 사용해야합니다. 그러나 당신은 그 외에 프로그램에서 많은 논리 오류를 가지고 있습니다. – RealSkeptic

+0

'row <= content.length' ... 그보다 작은 수는 없습니까? 'row

답변

0

하지만, 여기 당신이 시도할만한 해결책이 있습니다. 당신이 고심하는 것처럼 보였던 요점은 실제로 당신이 읽고 싶어하는 데이터를 가지고있는 파일의 단 한 줄 밖에 없다는 것입니다.

line.split(" \\| ?") 

이 우리가 예를 들어 양식 28|32에 문자열 잎 : 나는 다음과 같은 정규 표현식을 사용하여 행을 분할합니다. 이 고/저 쌍 각각은 파이프를 사용하여 다시 분할 할 수 있습니다 (그러나 조심해서 파이프를 탈출해야합니다 (예 : \\|). 마지막으로, 데이터를 배열에 저장하고 끝에 온전한 체크로 출력 할 수 있습니다.

public static void main(String[] args) { 
    String line; 
    String file = "temperature.txt"; 
    int[][] temp = new int[10][2]; 
    FileReader fr = null; 
    BufferedReader br = null; 

    try 
    { 
     fr = new FileReader(file); 
     br = new BufferedReader(fr); 

     // eat the first three lines, as they don't contain data you want to use 
     br.readLine(); 
     br.readLine(); 
     br.readLine(); 
     line = br.readLine(); 
     System.out.println("Analysis report of the temperature reading for the past 10 days " + line); 

     String [] content=line.split(" \\| ?"); 
     for (int i=1; i < content.length; ++i) { 
      String[] pair = content[i].split("\\|"); 
      temp[i-1][0] = Integer.parseInt(pair[0]); 
      temp[i-1][1] = Integer.parseInt(pair[1]); 
     } 
     System.out.println(Arrays.deepToString(temp)); 

    } 
    catch (Exception e) { 
     System.out.println("An exception occurred."); 
    } 
} 
관련 문제