繁体   English   中英

如何使用Java将文本文件中的数据读取到数组中,跳过某些元素

[英]How to read data from a text file into arrays in Java, skip certain elements

我需要为课堂上要做的作业提供帮助。 我只是刚开始使用Java,所以我对它很陌生。 我需要编写一个代码,该代码将扫描文本文件中的数字,然后计算它们并创建一些平均值。 我使用了for循环来扫描文件,但是我不知道如何扫描它,因此它跳过了每三行。 我需要文本的每一列而不是每一行。 文本文件包含3列和7行。

public static void main(String [] args){
    readData("Sample.in");
}

static void readData(String fileName){
    try{
        int[] breakfast= new int[7];
        int[] lunch=new int[7];
        int[] dinner= new int[7];

        File input = new File(fileName);        // Creates Scanner to read line from the text file
        Scanner scanLine = new Scanner(input);  // Reads entire line from the file

        String line= scanLine.nextLine();       // To read numbers from the Line buffer

        Scanner scanNumber = new Scanner(line); // to read three numbers from the line buffer

        for(int meal =0; meal<3; meal++){       // Checks whether the number is present in the line
            if(scanNumber.hasNextInt()){        // read number from the line buffer and store it in the calories variable

                int calories = scanNumber.nextInt();
                System.out.print(calories+" ");

            }
        }
        System.out.println("");
    } catch(FileNotFoundException e){                   // catches exception in case the file is missing
        System.out.println(e);
    }
}

输入文件示例:

200 1000 800 
450 845 1200
800 250 400 
0 1500 1800
600 500 1000
700 1400 1700
675 400 900

这是一个非代码解决方案

  1. 打开文件。
  2. 创建扫描仪。
  3. 同时(scanner.hasNextLine())
  4. 使用扫描仪读取一行。
  5. 使用String.split()分割行; //阅读api并使用符合您要求的split版本。
  6. split返回一个数组。 您关心元素0、1和2。
  7. 将元素0、1和2转换为整数(请参阅api文档中的Integer)。
  8. 将元素0、1和2添加到列表中。

一些java进:

List<Integer> breakfast = new ArrayList<Integer>();
List<Integer> dinner = new ArrayList<Integer>();
List<Integer> lunch = new ArrayList<Integer>();

// add an element to breakfast:
breakfast.add(blammy);

// Iterate through dinner:
int dinnerTotal = 0
for (Integer current : dinner)
{
    dinnerTotal += current.intValue();
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM