简体   繁体   English

如何修复try块,以便从txt文件获取平均值?

[英]How do I fix my try block so I get the average from my txt file?

so I am trying to read and find the average of all these integers from a normal .txt file, this is how it looks: 所以我试图从普通的.txt文件中读取并找到所有这些整数的平均值,这就是它的样子:

Mary 60
Tom 70
Jack 80
John 90
Sue 100
Bob 95
Gary 85
Emily 75

I have the read part down, but something is wrong with either my while loop or my try block 我的阅读部分掉了下来,但我的while循环或try块出了点问题

This is my desired output: The average is 81.0 这是我想要的输出: The average is 81.0

This is my actual output: 这是我的实际输出:

The average is 7.0 The average is 8.0 The average is 10.0 The average is 11.0 The average is 12.0 The average is 11.0 The average is 10.0 The average is 9.0

Can anybody find the error in my logic? 有人能在我的逻辑中找到错误吗?

public class Average {//begin class

public static void main(String[] args) {//begin main
    // TODO Auto-generated method stub

    try {//begin try
        File datafile = new File("C:\\Users\\jglez\\Documents\\Data.txt");
        Scanner inputFile = new Scanner(datafile);
        while(inputFile.hasNext()) {
            String name = inputFile.next();
            int grade = inputFile.nextInt();
            double average = grade/8;

            System.out.println("The average is " + average);
        }//end while

    }//end try
    catch(Exception e) {//begin catch
        System.out.println("FileNotFoundException caught");
    }//end catch

}//end main
    }//end class

I tried placing 我尝试放置

double average = grade/8; System.out.println("The average is " + average);

outside of my try while loop and before my try block because I think it should work logically like that, but I get the error "grade cannot be resolved to a variable" even though I declared it in my while loop, so I don't know what's the fix? 在try while循环之外和try块之前,因为我认为它应该在逻辑上这样工作,但是即使我在while循环中声明了它,也收到错误“等级无法解析为变量”,所以我没有知道解决办法吗?

I appreciate any help, thanks! 感谢您的帮助,谢谢!

Let see. 让我们看看。

I tried placing [code] outside of my try while loop and before my try block because I think it should work logically like that, but I get the error "grade cannot be resolved to a variable" even though I declared it in my while loop, so I don't know what's the fix? 我尝试将[code]放在try while循环之外和try块之前,因为我认为它应该在逻辑上这样工作,但是即使我在while循环中声明了“等级无法解析为变量”,我仍然收到错误消息,所以我不知道解决办法是什么?

Well, grade is declare in the while loop so grade only exist in that block. 好吧, grade是在while循环中声明的,因此grade仅存在于该块中。 Explaining why you can't access it outside. 解释为什么您无法在外部访问它。


Your math is wrong 你的数学错了

double average = grade/8

In java, int / int will always give you a int , so you will loose the decimal value. 在java中, int / int始终会给您一个int ,因此您将丢失十进制值。 You can correct that with grade / 8.0 because int / double gives a double . 您可以使用8. grade / 8.0更正此问题,因为int / double提供double

double average = grade / 8.0

Note that an average should be the sum of all value divide by the amount of value so the loop should do two thing : 注意,平均值应该是所有值的总和除以值的数量,因此循环应做两件事:

  • Sum every grade in a variable 对变量中的每个grade求和
  • Count the number of grade 计算grade

Then you just need to divide the sum by the count to get the average 然后,您只需要将总和除以计数即可得出平均值

 int sum = 0, count = 0;

 Scanner inputFile = new Scanner(datafile);
 while(inputFile.hasNext()) {
      String name = inputFile.next();
      int grade = inputFile.nextInt();
      sum = sum + grade;
      count++;
 }//end while

 double average = 1.0 * sum / count;

Considering files can have any number of records, it is better to count them rather than hard-coding as 8 . 考虑到文件可以有任意数量的记录,因此最好将它们计数而不是将其硬编码为8 Make sure integer summation does not overflow otherwise use BigInteger . 确保整数求和不会溢出,否则请使用BigInteger Division of two ints will result in int result, you have to typecast it into float or double. 将两个整数相除会得到整数结果,您必须将其转换为float或double。

Changes to be made, declare countLines to count records in the file and sumOfGrades to hold summation of grades. 要进行更改,请声明countLines以对文件中的记录进行计数,并声明sumOfGrades以保存成绩的总和。 Once file scan is complete, declare variable average and compute it using sumOfGrades/countLines with typecase to get the result. 文件扫描完成后,声明变量average并使用sumOfGrades/countLines计算得出结果。

try {//begin try
            File datafile = new File("C:\\Users\\jglez\\Documents\\Data.txt");
            Scanner inputFile = new Scanner(datafile);
            int sumOfGrades = 0;
            int countLines = 0; // to calculate number of lines file has.
            while(inputFile.hasNext()) {
                String name = inputFile.next();
                int grade = inputFile.nextInt();
                sumOfGrades += grade;
                ++countLines;
            }//end while
            double average = (double) sumOfGrades/countLines;
            System.out.println("The average is " + average);
        }//end try
        catch(Exception e) {//begin catch
            System.out.println("FileNotFoundException caught");
            e.printStackTrace();
        }//end catch

so I don't know what's the fix? 所以我不知道解决办法是什么?

I am not going to tell you the fix. 我不会告诉您解决方法。 It is more important that you understand what your answer is wrong ... so that you can learn from your mistakes. 更重要的是,您要了解答案是错误的……以便您可以从错误中学习。

So let's step back. 因此,让我们退后一步。

The formula for calculating an average of a set of numbers is: 计算一组数字的平均值的公式为:

average = total sum of all the numbers / number of items in the set. 平均值=集合中所有数字的总和/项目数。

(You should have learned this in high school maths, if not before!) (如果没有,您应该在中学数学中学到的!)

Now let us compare this with what you are doing in your code: 现在,让我们将此与您在代码中所做的比较:

    int grade = inputFile.nextInt();
    double average = grade/8;
    System.out.println("The average is " + average);

What is wrong with that? 怎么了

Problem #1: 问题1:

You are not calculating the sum of all the numbers. 您不是在计算所有数字的总和。 The grade is the value you just read. grade是您刚刚阅读的值。 Not the sum. 不是总和。 (Summing means you need to add up the grades!) (总结意味着您需要累计成绩!)

Problem #2: 问题2:

You are assuming that the number of items is 8: 您假设项目数为8:

  • If the file doesn't contain 8 items, that is not true. 如果文件不包含8个项目,则不正确。

  • When you are computing and outputting a running average (as you are currently doing), you should be dividing by the number of elements read so far . 在计算和输出运行平均值时 (如当前所做的那样),应除以到目前为止读取的元素数。

Hint: count them. 提示:算一下。

Problem #3: 问题3:

This problem is a bit more subtle. 这个问题更加微妙。

Since grade is an integer and 8 is an integer, grade / 8 is an integer division. 由于grade是整数, 8是整数,所以grade / 8是整数除法。 That means that the result is truncated. 这意味着结果将被截断。 For example, 60 / 8 gives you 7 ... not 7.5 . 例如, 60 / 8给您7 ...而不是7.5

If you want an accurate floating point result, you need one of the operands of the / operator to be a floating point value. 如果要得到准确的浮点结果,则需要/运算符的操作数之一作为浮点值。 For example 例如

  int sum = 60;
  int count = 8;
  double average = sum / count;            // INCORRECT answer - `7.0`
  double average = ((double) sum) / count; // CORRECT answer   - `7.5`

If you understand the above 3 problems, you should be able to figure out how to solve them, and make your program work. 如果您了解上述3个问题,则应该能够弄清楚如何解决它们,并使程序正常运行。

Many changes required. 需要进行许多更改。 Following is the resulted try block. 以下是所得的try块。 You can find comments inline 您可以在线找到评论

try {//begin try
        File datafile = new File("C:\\Users\\jglez\\Documents\\Data.txt");
        Scanner inputFile = new Scanner(datafile);
        double average=0; //Intializing average outside
        while(inputFile.hasNext()) {
            String name = inputFile.next();
            double grade = inputFile.nextDouble(); //Changed datatype to double
            average = average +  grade/8.0; //changed your average calculation


        }
        System.out.println("The average is " + average); //Printing average outside

I think you are trying to divide each value with the count which is not appropriate instead you need to find sum of all elements and divide it by count and your code should change something as below: 我认为您正在尝试将每个值除以不适当的计数,相反,您需要找到所有元素的总和,然后将其除以计数,您的代码应进行如下更改:

public class Average {//begin class

public static void main(String[] args) {//begin main
    // TODO Auto-generated method stub

    try {//begin try
        double sum=0.0,grade =0.0;
        File datafile = new File("C:\\Users\\jglez\\Documents\\Data.txt");
        Scanner inputFile = new Scanner(datafile);
        while(inputFile.hasNext()) {
            String name = inputFile.next();
            grade = inputFile.nextInt();
            sum = sum+grade;


        }//end while
        System.out.println("The average is " + sum/8.0);
    }//end try
    catch(Exception e) {//begin catch
        System.out.println("FileNotFoundException caught");
    }//end catch

}//end main
    }

Hope this is helpful and try to include arithmetic exception catch clause for above logic. 希望这会有所帮助,并尝试为上述逻辑包括算术异常捕获子句。

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

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