如果輸入2個.txt文件以外的錯誤響應,則代碼應該顯示文件'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;
}
}
}
}
有正確鍵入文件名?你確定可執行文件和文件在同一個目錄中嗎? –
是的可執行文件和一切正常,當你輸入錯誤的.txt名稱我需要它說文件'double_input3.txt'不存在。請再次輸入文件名稱,但也包括請輸入文件名稱。 – akay