输入2 .txt文件以外的错误响应后,代码应该说File' double_input3.txt'不存在。请再次输入文件名:但它还添加请再次输入文件名。
import java.util.Scanner;
import java.io.*;
import java.text.DecimalFormat;
public class boost
{
public static void main(String[] args) throws IOException
{
double sum = 0.0;
double count = 0.0;
double avg = 0.0;
while (true)
{
@SuppressWarnings("resource")
Scanner keyboard = new Scanner(System.in);
System.out.print("Please enter the file name: \n");
String filename = keyboard.nextLine();
if(filename.equals(null)){
break;
}
File file = new File(filename);
if (!file.exists()){
System.out.println("File 'double_input3.txt' does not exist ");
System.out.println("Please enter the file name again:");
continue;
}
Scanner inputFile = new Scanner(file);
DecimalFormat df = new DecimalFormat();
df.setMaximumFractionDigits(3);
while (inputFile.hasNext())
{
double number = inputFile.nextDouble();
sum = sum + number;
count++;
avg = ((double) sum / count);
}
System.out.println("Total: " + df.format(sum));
System.out.println("Average: "+ df.format(avg));
inputFile.close();
if (file.exists()){
break;
}
}
}
}
答案 0 :(得分:0)
移动此行
System.out.print("Please enter the file name: \n");
在while
循环之前,以便它只打印一次
修改强>
此代码有效
System.out.print("Please enter the file name: \n");
while (true)
{
@SuppressWarnings("resource")
Scanner keyboard = new Scanner(System.in);
String filename = keyboard.nextLine();
if(filename.equals(null)){
break;
}
File file = new File(filename);
if (!file.exists()){
System.out.println("File 'double_input3.txt' does not exist ");
System.out.println("Please enter the file name again:");
continue;
}
break;
}
System.out.println("finsihed");
<强>输出强>
Please enter the file name:
nothere
File 'double_input3.txt' does not exist
Please enter the file name again:
c:/temp/a.txt
finsihed