2017-09-10 17 views
0

我的代碼工作正常,完全按照它應該在NetBeans上,但是當我使用CMD時,它不會執行像netbeans上的所有操作。第一個try/catch應該計算它在txt文件上讀取某些內容的次數。 NetBeans上它工作正常,但在CMD它保持0爲什麼我的代碼在netbeans上運行時會讀取文件,而在CMD上運行時卻不會運行?

import java.io.*; 
import java.io.FileNotFoundException; 
import java.util.Scanner; 
import java.util.NoSuchElementException; 
public class Calories { 


public static void main(String[] args) throws NoSuchElementException { 



    String file = "input.txt"; 
    String text = ""; 
    double [] breakfast = new double [7]; 
    double [] lunch = new double [7]; 
    double [] dinner = new double [7]; 
    int counter = 0; 


    try { 
     Scanner input = new Scanner(new File("input.txt")); 

     while(input.hasNextInt()) { 
     int number = input.nextInt(); 
     System.out.println(number); 
     counter++; 
    } 

    } catch (Exception ex) { 

    } 

    //If the file is missing a number or has an extra the program will tell the user and will exit 
    if (counter != 21) { 
     System.out.println("Counter " + counter); 
     System.out.println("Your file will not work with this program. Please try again."); 
      System.exit(0); 
    } 

    //this is going to attempt to read from file "input.txt" 
    //if file cannot be found user will be told the it cannot be found 
    try { 
     Scanner s = new Scanner(new File(file)); 
     while (s.hasNextInt()) { 
      for (int i = 0;i<7;i++) 
      { 
       breakfast[i] = s.nextInt(); 
       lunch[i] = s.nextInt(); 
       dinner[i] = s.nextInt(); 


      } 

     } 

    } 

    //this catch will execute if the file name is incorrect 

    catch(FileNotFoundException e) { 
     System.out.println("file not found"); 
    } 



    //calling all of the methods I created here 

    getCal(breakfast, lunch, dinner); 
    getDays(breakfast, lunch, dinner); 
    getAvg(breakfast, lunch, dinner); 
    //exits program once it has finished executing the methods 
    System.exit(0); 
} 

我用盡了一切的聲明價值,據我所知,但我仍然不知道這一點。

+0

等等。它不執行?或者它不編譯?請清楚這一點,因爲你的問題提到了兩者。如果這是一個執行問題,你看到了什麼異常/錯誤信息? –

+0

我不得不懷疑這是由於Java在哪裏查找文件,「user.dir」在哪裏,並且您最好使用資源而不是文件。 –

+0

我的歉意,它執行,但首先嚐試/趕上它應該讀通過一個文件,並計數每次它讀取的東西。在netbeans中,它執行得很好,但是在命令中,它使計數器保持初始值0. –

回答

0

當你在命令行中運行它,然後你的代碼期望input.txt文件是從正在運行的java [PROGRAM_NAME] [FILE_NAME]命令

相同的目錄如果你把這個文件在同一目錄它將很好地工作。

另一方面,如果將Netbeans放置在項目根目錄中,Netbeans將自行處理文件路徑的解析。

"input.txt"此名稱不會告訴你有關文件放置位置的任何信息。這取決於他們試圖找到這個文件的Netbeans或命令行。

如果您使用項目資源路徑或類似於相對路徑的東西,它將嘗試在那裏找到它,並且它將有一個信息在哪裏找到該文件。

同樣,如果你將文件的絕對路徑文件將在該路徑中搜索。

但是在這裏你沒有提供任何關於路徑的信息。

+1

就是這樣。謝謝一堆。 –

相關問題