读取文本文件中的下一行 [英] Reading the next line in a text file

查看:90
本文介绍了读取文本文件中的下一行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从文本文件中读取输入,该文件的格式如下:

I'm trying to read input from a text file that will be formatted like this:

2 80 97 
5 69 79 89 99 58 
7 60 70 80 90 100 0 59

每行的第一个数字是每个部分"的等级"数.

The first number of each line is the number of "grades" per "section."

我让程序读取一个部分,但是我不知道如何使它读取将要有多少个部分,然后读取下一行.

I got my program to read one section, but I can't figure out how to make it read how many sections there will be, and then read the next line(s).

我想我可以将当​​前代码放入计数控制的循环中,该循环将首先读取有多少部分,然后运行该循环多次.我只是不知道如何将这个想法转换为代码.

I think I can put my current code in a count controlled loop that will first read how many sections there are, and run the loop that many times. I just don't know how to convert that idea to code.

这是revevant代码部分:

Here is the revevant code section:

public static void main(String args[]) throws Exception 
{
  Scanner in = new Scanner(new File("prog2test.txt")); 

  //int sections = (in.nextInt());
  int scores = (in.nextInt());
  int scoresForAverage = scores;
  int scoreTotals = 0;
  double average = 0;
  int A = 0;
  int B = 0;
  int C = 0;
  int D = 0;
  int F = 0;

  int highest = 0;
  int lowest = 100;
  while (scores > 0 && in.hasNextInt())
  {
     int grade = in.nextInt();
     if (grade >= 90)
        A++;
     else if (grade >= 80)
        B++;
     else if (grade >= 70)
        C++;
     else if (grade >= 60)
        D++;
     else
        F++;

     if (grade > highest) 
        highest = grade;
     if (grade < lowest)
        lowest = grade;

     scores--;
     scoreTotals = (scoreTotals + grade);
   }  

  average = scoreTotals/scoresForAverage;

  System.out.println("Scores for section 1");
  System.out.println("A's: " + A);
  System.out.println("B's: " + B);
  System.out.println("C's: " + C);
  System.out.println("D's: " + D);
  System.out.println("F's: " + F);
  System.out.println("Lowest score: " + lowest);
  System.out.println("Highest score: " + highest);
  System.out.println("Average: " + average);

已更新完整方法.

推荐答案

由于您知道每行ISNT的第一个int是成绩,因此可以使用 someString = in.nextLine()保存每行 in.hasNextLine()时,然后使用新的 Scanner 实例为每行遍历每个保存的字符串,跳过第一个整数.

Since you know the first int in each line ISNT a grade, you can save each line using someString = in.nextLine() while in.hasNextLine() and then iterate over each saved string skipping the first integer using a new Scanner instance for each line.

这篇关于读取文本文件中的下一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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