【发布时间】:2017-10-25 01:14:39
【问题描述】:
这是我的代码:
import java.io.*;
import java.util.Scanner;
import java.text.DecimalFormat;
public class QuestionTwo
{
public static void main(String[] args) throws IOException
{
String file;
Float number;
String File;
double avgnumbers;
DecimalFormat formatter = new DecimalFormat("##.##");
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter a file name");
file = keyboard.nextLine();
FileReader freader = new FileReader(file);
BufferedReader inputFile = new BufferedReader(freader);
while(file != ("input.txt"))
{
System.out.println("File is not found, enter the filename again.");
file = keyboard.nextLine();
}
System.out.println("The number to check: ");
number = keyboard.nextFloat();
String inp = inputFile.readLine();
int count = 0;
int sum = 0;
while (inp != null)
{
int strnumber = Integer.parseInt(inp);
if(strnumber > number)
{
sum += strnumber;
count++;
}
inp = inputFile.readLine();
}
avgnumbers = (double)sum / count;
System.out.println("The average of the numbers that are greater than " + number + " is " + avgnumbers);
inputFile.close();
}
}
我在使用此代码时遇到的问题是,当我为第一个问题编写错误的文件名时,我得到了一个异常。我编码的目的是让它告诉我那是错误的,我应该重新输入文件名,以便它可以这样做。然后理论上它会无限地这样做,直到输入正确的文件名(input.txt);我想指出我的代码的结果是我喜欢的并且符合它的要求;只是它一直显示这个异常。它对要求文件名的代码的另一部分做了这件事,所以也许这与此有关。虽然在我凭直觉改变任何东西之前,我想获得一些“同行评审”;任何帮助将不胜感激。
异常堆栈:
[DrJava Input Box]
java.io.FileNotFoundException: dxfgb (The system cannot find the file
specified)
at java.io.FileInputStream.open0(Native Method)
at java.io.FileInputStream.open(Unknown Source)
at java.io.FileInputStream.<init>(Unknown Source)
at java.io.FileInputStream.<init>(Unknown Source)
at java.io.FileReader.<init>(Unknown Source)
at QuestionTwo.main(QuestionTwo.java:31)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at
edu.rice.cs.drjava.model.compiler.JavacCompiler.runCommand(JavacCompiler.jav 一个:267)
【问题讨论】:
-
异常在哪里?请发布调用堆栈。
-
要比较字符串,请使用
file.equals("input.txt")之类的内容。如果你使用==或!=,它会比较对象引用,它总是false -
请修正您的格式。也许将代码减少到必要的位。见How to create a Minimal, Complete, and Verifiable example(强调Minimal)。