NetbeansでJavaプロジェクトを構築しています。私はデータファイル(temperature.txt)に高低のテンポラリを含む形式(低)|(高)を持っています。ファイルは2次元配列に読み込まれ、画面に表示されます。しかし、私は私のJavaプロジェクトを実行すると、私はこのエラーに遭遇し、完全に失われています。しかし、私はこの問題を解決する方法を知らない。スレッド "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");
}
}
}
}
}
どの行が48ですか? – bradimus
'split()'は* regex *を使うことを知っておくべきです。そのため、 '|'は特殊文字で、 "どちらか、それともどちらか"という区切り文字を探すように指示します。これはあなたが意図したものではありません。代わりに '\\ |'を使用してください。しかし、それ以外にもあなたのプログラムには多くの論理エラーがあります。 – RealSkeptic
'row <= content.length' ...それだけではならないでしょうか? 'row