gpt4 book ai didi

java - 如何防止代码重播相同的消息?

转载 作者:太空宇宙 更新时间:2023-11-04 11:38:11 25 4
gpt4 key购买 nike

输入除 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;
}
}



}
}

最佳答案

移动此行

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

关于java - 如何防止代码重播相同的消息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43059716/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com