【问题标题】:Read and print from a text file从文本文件读取和打印
【发布时间】:2013-10-12 06:17:50
【问题描述】:

好的,所以我应该使用代码从文本文件中读取和打印,但每次运行时,我都会在第 31 行“grade = in.nextInt();”上得到一个“java.utilNoSuchElementException”。当前的文本文件是 2 80 97 5 69 79 89 99 58 7 60 70 80 90 100 0 59

其中第一个数字是每个部分的分数数,每个部分都应该被计算(即1、2、3)无论如何一次一个问题。这是当前代码。

导入 java.util.Scanner; 导入 java.io.*;

公开课 Prog2 {

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

    int Lowest, Highest, grade = 0;
    float section_average, class_average;
    int count = 0, A = 0, B = 0, C = 0, D = 0, F = 0, total_number_of_sections = 0, total_number_of_scores = 0, number = 0;
    while (in.hasNextInt())
    {
        number = in.nextInt();
        System.out.println (in.nextInt());
        number ++;

        while (count < number)
        {
            grade = in.nextInt();
            total_number_of_sections += number;
            total_number_of_scores += grade;
            total_number_of_scores ++;

            count++;


        }

    }
    if (number > 0)
    {
        System.out.println ("Scores for section "+count);
    }
    else
    {
        System.out.println ("Scores for section 0");
    }
    if (grade >= 90)
    {
        A ++;

    }
    if (grade >= 80 && grade < 90)
    {
        B ++;

    }
    if (grade >= 70 && grade < 80)
    {
        C ++;

    }
    if (grade >= 60 && grade < 70)
    {
        D ++;

    }
    if (grade < 60)
    {
        F ++;

    }
    System.out.println (" ");
    System.out.println ("Scores for section "+count);
    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: ");
    System.out.println ("Highest Score: ");
    System.out.println (" ");
    System.out.println (" ");
    System.out.println ("Total number of sections: " + total_number_of_sections);
    System.out.println ("Total number of scores: " + total_number_of_scores);
    System.out.println ("Class Average: ");



}

}

【问题讨论】:

  • 老兄,你在每次循环中都调用了两次“in.nextInt()”。调用它ONCE,保存值,然后打印你保存的变量。

标签: java text-files bluej sections


【解决方案1】:

试试这个

while (in.hasNextInt())
{
    count = 0;
    number = in.nextInt();
    System.out.println (in.nextInt());


    while (in.hasNextInt())
    {
        grade = in.nextInt();
        total_number_of_sections += number;
        total_number_of_scores += grade;
        total_number_of_scores ++;

        if(++count == number ){ break;}


    }

}

【讨论】:

  • 进入我的程序时只产生了 80 和 79。不过谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多