这段代码中是否存在违反语法的内容?

时间:2016-01-13 03:40:41

标签: java eclipse file-io while-loop java.util.scanner

该问题在文件中提供了6个整数,分为几行:

5
2
3
1
3
2

第1行描述了总天数,其他行描述了每天的小时数。我应该打印总天数和平均小时数。以下是我的代码:

import java.io.File;
import java.io.IOException;
import java.util.Scanner;

public class IFeelFine 
{
    public static void main(String[] args) throws IOException
    {
        File file = new File("Tax.txt");
        Scanner in = new Scanner(file);
        double count = in.nextInt();
        double total = 0;
        for (double i = 0; i < count; i++)
        {
            total += in.nextDouble();
        }
        double avg = total / count;
        System.out.println("Total vacation time missed: " + total + " hours");
        System.out.println("Average daily time missed: " + avg + " hours");
    }
}

当我运行此代码时,我在Eclipse中收到以下错误消息。

Exception in thread "main" java.util.NoSuchElementException
    at java.util.Scanner.throwFor(Unknown Source)
    at java.util.Scanner.next(Unknown Source)
    at java.util.Scanner.nextDouble(Unknown Source)
    at IFeelFine.main(IFeelFine.java:15)

这是什么意思,我需要修复什么来让程序运行? 任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:-1)

这是您的解决方案

import java.io.File;
import java.io.IOException;
import java.util.Scanner;

public class IFeelFine 
{
    public static void main(String[] args) throws IOException
    {
        File file = new File("Tax.txt");
        Scanner in = new Scanner(file);
        double total = 0;
        double avgTotal = 0;
        double counter = 0;
        int line = 0;
        while (in.hasNext())
        {
          if(line%2==0)
          {
            total += in.nextDouble();
          }
          else
          {
            avgTotal += in.nextDouble();
            counter ++;
          }
            line++;
            }
        double avg = avgTotal / counter;
        System.out.println("Total vacation time missed: " + total + " hours");
        System.out.println("Average daily time missed: " + avg + " hours");
    }
}

答案 1 :(得分:-2)

你的答案很好。这是测试结果:

std::queue

根据您的规则计算这些值是正确的。