我在打开文件和让我的程序读取文件中的整数时遇到问题。在下面的代码中,为了获取我的汽车数据,我可以随机生成它以获得汽车的持续时间以及汽车到达的机会。或者从文件中读取整数。该文件已由我们的教授提供,她就是文件中的内容:
37259 9819
46363 22666
46161 79934
5693 31416
91459 8272
72792 9493
83603 8372
77842 64629
84792 747
1299 178
显然,即使使用绝对路径我也无法打开文件,或者 data = dataFile.nextInt() 不是正确的使用格式。任何帮助将不胜感激我在这部分完全被难住了,我的整个程序工作但文件是我的致命弱点。
if (dataSource == 1) {
System.out.printf("Enter a filename \t :");
String aName = input.next();
java.io.File file = new java.io.File(aName);
try {
dataFile = new Scanner(file);
} catch (Exception e) {
System.out.println("Can't open file");
}
} else {
dataRandom = new Random();
System.out.println("Is Random Active");
}
input.close();
}
private void getCarData() {
if (dataSource == 1) {
int data1;
int data2;
data1 = dataFile.nextInt();
data2 = dataFile.nextInt();
anyNewArrival = (((data1%100) + 1) <= chancesOfArrival);
serviceDuration = (data2%maxDuration) + 1;
System.out.println("New Car has arrived with Duration Time: " + serviceDuration);//}
}
最佳答案
如果从 Netbeans 或 Eclipse 运行,您可以使用相对路径 "text.txt" 并确保您的文件结构是这样的
ProjectRoot
src
build
text.txt
关于java - 无法打开 .txt 文件以读取整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20297424/