2017-09-10 15 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

就是这样。谢谢一堆。 –

相关问题