如何防止代码重放相同的消息?

时间:2017-03-28 02:35:39

标签: java

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



   }
}

1 个答案:

答案 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