2017-03-28 29 views
1

如果輸入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; 
      } 
     } 



    } 
} 
+0

有正確鍵入文件名?你確定可執行文件和文件在同一個目錄中嗎? –

+0

是的可執行文件和一切正常,當你輸入錯誤的.txt名稱我需要它說文件'double_input3.txt'不存在。請再次輸入文件名稱,但也包括請輸入文件名稱。 – akay

回答

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 
+0

這個工作,但現在它使我按兩次輸入來打印答案 – akay

+0

通過移動打印語句不會導致任何額外的'按鍵'沒有在那裏。看看我編輯的代碼 –

+0

好的,非常感謝你的工作。 – akay