我的代码工作正常,与netbeans的应用完全相同,但是当我使用CMD时,它不像netbeans那样执行所有操作。第一个try / catch应该计算它在txt文件上读取内容的次数。在netbeans上它工作正常,但在CMD上它保持声明值为0。
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)
当您从命令行运行它时,您的代码希望input.txt
文件位于运行java [PROGRAM_NAME] [FILE_NAME]
命令所在的同一目录中
如果您将此文件放在同一目录中,它将正常工作。
另一方面,Netbeans自己处理它,如果你把它放在项目根目录中就是文件路径的解析。
"input.txt"
此名称并未告诉您文件放置位置的任何信息。它是Netbeans或命令行,他们试图找到这个文件。
如果你使用项目资源路径或类似相对路径的东西,它会尝试在那里找到它,并且它将有一个信息在何处找到该文件。
同样,如果您将为文件设置绝对路径,则将在该路径中搜索文件。
但是你没有提供有关路径的任何信息。