2

我需要帮助完成我必须为我的班级做的作业。我才刚刚开始使用 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
4

1 回答 1

1

这是一个非代码解决方案

  1. 打开文件。
  2. 创建扫描仪。
  3. while (scanner.hasNextLine())
  4. 使用扫描仪并读取一行。
  5. 使用 String.split() 分割线;// 读取 api 并使用符合您要求的拆分版本。
  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();
}
于 2013-09-11T18:44:08.893 回答