【问题标题】:Exception in thread “main” java.lang.ArrayIndexOutOfBoundsException: 1 [duplicate]线程“主”java.lang.ArrayIndexOutOfBoundsException 中的异常:1 [重复]
【发布时间】:2016-11-16 14:00:15
【问题描述】:

我正在 Netbeans 中构建一个 java 项目。我得到了我的数据文件(temperature.txt),其中包含格式为 (low)|(high) 的高温和低温。该文件应加载到二维数组中,然后将其打印到屏幕上。但是当我运行我的java项目时,我遇到了这个错误并且完全迷失了。但我不知道如何解决这个问题。

温度.文本:

+-------------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+
| 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行是哪一行?
  • 你应该知道split()使用了一个regex。因此,| 是一个特殊字符,它告诉它寻找一个定界符,即“要么这个要么那个”,在这种情况下,“要么没有,要么什么都没有”。这不是你想要的。您应该改用\\|。但是除此之外,您的程序中还有许多逻辑错误。
  • row&lt;=content.length ...不应该小于吗? row &lt; content.length
  • 您应该在for 循环中使用row &lt; content.length 而不是row &lt;= content.length。有效的数组索引从 0 到长度 - 1。
  • 你试过调试代码吗?

标签: java arrays string int stringtokenizer


【解决方案1】:

我不知道您是否已经问过这个问题,但这里有一个可行的解决方案供您尝试。您似乎在挣扎的关键点是文件中只有一行实际上包含您想要读取的数据。我使用以下正则表达式分割这一行:

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.");
    }
}

【讨论】:

    猜你喜欢
    • 2021-06-13
    • 1970-01-01
    • 2013-12-18
    • 2021-02-19
    • 2015-06-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多