程序计算来自文件的数字的平均值(涉及try/catch块)

huangapple go评论121阅读模式
英文:

Program that computes average of numbers from a file (try/catch blocks involved)

问题

以下是您提供的代码的翻译部分:

package average;
import java.io.*;
import java.util.Scanner;

public class Try {
    static Scanner inFile;

    public static void main(String[] args) throws IOException {
        int fileTry = 0;
        String fileName;
        Scanner inName = new Scanner(System.in);
        System.out.println("Enter file name>");
        fileName = inName.nextLine();
        boolean fileOk;
        do {
            fileOk = false;
            try {
                Scanner file = new Scanner(new File(fileName));
                fileOk = true;
            } catch (FileNotFoundException error) {
                System.out.println("Reenter file name>");
                fileName = inFile.nextLine();
                fileTry++;
            }
        } while (!fileOk && fileTry < 4);
        PrintWriter outFile = new PrintWriter(new FileWriter("outNumbers.dat"));

        if (fileName != null) {
            int numDays = 0;
            double average;
            double inches = 0.0;
            double total = 0.0;
            while (inFile.hasNextFloat()) {
                inches = inFile.nextFloat();
                total = total + inches;
                outFile.println(inches);
                numDays++;
            }

            if (numDays == 0)
                System.out.println("Average cannot be computed " +
                        " for 0 days.");
            else {
                average = total / numDays;
                outFile.println("The average rainfall over " +
                        numDays + " days is " + average);
            }
            inFile.close();
        } else
            System.out.println("Error");
        outFile.close();
    }
}

请注意,翻译文本仅包括您提供的代码部分,不包含额外的回答或解释。如果您有任何进一步的问题或需要帮助,请随时提问。

英文:

I have a program that is supposed to allow the user to enter a file name, which, if correct, computes the average of the numbers within the file and prints it out. Likewise, if the user enters the wrong file name a certain number of times, then the program quits. In the program, the "try" block is supposed to instantiate the Scanner and set fileOk to true, while the "catch" block is supposed to prompt the user to reenter the file name, read the file, and increment fileTry. The first "if" statement is also supposed to make it so the average is calculated or an error message is written on the output file (outNumbers.dat). Here is the code I have so far:

package average;
import java.io.*; 
import java.util.Scanner; 
public class Try
{
static  Scanner inFile;
public static void main(String[] args) throws IOException
{
int fileTry = 0;
String fileName;
Scanner inName = new Scanner(System.in);
System.out.println(&quot;Enter file name&gt;&quot;);
fileName = inName.nextLine();
boolean fileOk;
do
{
fileOk =  false;
try
{
Scanner file = new Scanner(new File(fileName));
fileOk = true;
}
catch(FileNotFoundException error)
{
System.out.println(&quot;Reenter file name&gt;&quot;);
fileName = inFile.nextLine();
fileTry++;
}
} while (!fileOk &amp;&amp; fileTry &lt; 4);
PrintWriter outFile = new PrintWriter(new FileWriter(&quot;outNumbers.dat&quot;));
if (fileName != null )
{	
int numDays = 0;
double average;
double inches = 0.0;
double total = 0.0;
while (inFile.hasNextFloat())
{
inches = inFile.nextFloat();
total = total + inches;
outFile.println(inches);
numDays++;
}
if (numDays == 0) 
System.out.println(&quot;Average cannot be computed &quot; +
&quot; for 0 days.&quot;); 
else
{
average = total / numDays;
outFile.println(&quot;The average rainfall over &quot; +  
numDays + &quot; days is &quot; + average); 
}
inFile.close();
}
else
System.out.println(&quot;Error&quot;);
outFile.close();
}
}

And here is the contents of the correct file(inNumbers.dat):

2.3 
3.1 
0.3 
1.1 
2.2 
2.1 
0.0 
0.4 
0.76 
0.5 
1.0 
0.5

This is the output I get after running the program and entering the correct file name:

Enter file name&gt;
inNumbers.dat
Exception in thread &quot;main&quot; java.lang.NullPointerException
at average.Try.main(Try.java:40)

I am a bit lost on how to fix this :/

答案1

得分: 0

NullPointerException在Java中非常常见。它通常意味着你正试图使用一个从未初始化过的对象。在这种情况下,infile只是被声明了但从未初始化。

Scanner file = new Scanner(new File(fileName));

file变量只存在于try块内,因为它是在那里声明的。你可能想要初始化infile

infile = new Scanner(new File(fileName));
英文:

NullPointerException is very common in java. It often means that you are trying to work with an object that was never initialized. In this case, infile is only declared and never initialized.

Scanner file = new Scanner(new File(fileName));

The file variable only exists within the try block, since that's where it was declared. You probably wanted to initialize infile instead.

infile = new Scanner(new File(fileName));

huangapple
  • 本文由 发表于 2020年4月7日 04:49:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/61068726.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定