尝试将文本文件读入2D数组并打印到屏幕 [英] Trying to read text file into a 2D Array and print to screen

查看:64
本文介绍了尝试将文本文件读入2D数组并打印到屏幕的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图从文件中读取数据并加载到二维数组中,然后将其打印到屏幕上,但是输出错误:

I'm trying to read data from a file and load into a two dimensional array and then print it to the screen but I got the wrong output:

输出:

Analysis report of the temperatre reading for the past 10 days 
The code throws an exception
The code throws an exception
The code throws an exception
The code throws an exception
The code throws an exception
The code throws an exception
The code throws an exception
The code throws an exception
The code throws an exception

I创建了一个名为temperature.txt的数据文件。数据文件包含高&过去10天的低温(格式)(低)| (高):

+-------------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+
| 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 |
+-------------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+

这是我的以下代码:

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

public class Temperature {


    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);


            for(int row=0; row<temp.length; row++)
            {
               tokenizer=new StringTokenizer(line, "|");

               if(row != 0)
               {
                   try
                   {

                       if(row % 2 == 0)
                       {
                           sumHigh = Integer.parseInt(tokenizer.nextToken());
                           temp[row][1]=Integer.parseInt(tokenizer.nextToken());

                       }
                       else if (row % 2 != 0) 
                       {

                           sumLow = Integer.parseInt(tokenizer.nextToken());
                           temp[row][0]=Integer.parseInt(tokenizer.nextToken());

                       }
                   }
                   catch(Exception e)
                   {
                       System.out.println("The code throws an exception");
                   }
               }

            }

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


    }

}


推荐答案

我将把解析温度的逻辑移到一个单独的函数中。像这样:

I would move out the logic that parses the temperatures into a separate function. Like this:

public class Temperature {
    public static class MinMax {
        private int min;
        private int max;

        public MinMax(int min, int max) {
            this.min = min;
            this.max = max;
        }

        public int getMin() {
            return this.min;
        }

        public int getMax() {
            return this.max;
        }
    }

    private static List<MinMax> getTemperatures(String line) {
        List<MinMax> minMaxList = new ArrayList<>(10);

        StringTokenizer tokenizer = new StringTokenizer(line, "|");
        System.out.println(tokenizer.nextToken().trim());  //prints out Temperature
        while(tokenizer.hasMoreTokens()) {
            int minimum = Integer.valueOf(tokenizer.nextToken().trim());
            int maximum = Integer.valueOf(tokenizer.nextToken().trim());
            minMaxList.add(new MinMax(minimum, maximum));
            System.out.println("Day " + (minMaxList.size()) + ": Minimum: " + minimum + " Maximum: " + maximum);
        }

        return minMaxList;
    }

    public static void main(String[] args) {
        getTemperatures("| Temperature | 30|32 | 29|30 | 25|28 | 25|29 | 27|31 | 28|32 | 26|30 | 24|32 | 24|41 | 27|32 |");
    }
}

我不确定您要如何存储二维数组中的温度,因此为其创建了一个专用的类并返回了列表中的所有内容。然后,您可以根据需要将此列表放入数组结构。

I wasn't sure how you would like to store the temperatures in a 2d array, so rather made a dedicated class for it and returned everything in a list. You can then take this list and put it into an array structure if you like.

还请注意,我使用了 trim()删除数字周围的空格。这样可以防止您获取NumberFormatException。

Also notice I used trim() to remove the whitespace surrounding the numbers. This prevents you from getting a NumberFormatException.

这篇关于尝试将文本文件读入2D数组并打印到屏幕的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆