【发布时间】:2019-04-02 22:40:04
【问题描述】:
我的班级项目是提示用户输入一个文件,他们输入的那个文件名必须是正确的,一旦文件建立起来,文件的第一行就是数组的大小。然后,我必须将每个值逐行分配给数组。
快速说明**我们还没有了解缓冲阅读器,所以我不能使用它。我也不能用ArrayList,还没有讲到。
问题:我如何确保他们输入的文件名是正确的?到目前为止,我们在课堂上使用了 while 循环来检查,但我想知道是否有更好的方法。我需要用户输入“investments.txt”,否则我需要一次又一次地提示他们。也非常感谢改进现有代码的任何要点,我对此很陌生。
到目前为止的代码:
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.Scanner;
public class Prog07_InvestmentManager {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Please enter the file name to import. Example: Investments.txt."); //prompt user
File file = new File(in.nextLine());
try {
Scanner inFile = new Scanner(new FileReader("investments.txt"));
double min = Integer.MAX_VALUE;
double max = 0;
double mean = 0;
int num = inFile.nextInt();
inFile.nextLine();
double line = 0;
int sum = 0;
int count = 0;
while (inFile.hasNextLine()) {
line=inFile.nextDouble();
sum+=line;
count++;
if(line>max)
max=line;
if(line<min)
min=line;
}
mean = (sum/count);
System.out.println("Max: "+max);
System.out.println("Min: "+min);
System.out.println("Mean: "+mean);
System.out.println();
} catch (FileNotFoundException e1) {
}
if (in.hasNextDouble()) {
double[] values = new double [(int) in.nextDouble()];
}
try {
Scanner inputFile = new Scanner(file);
double[] arr = new double[(int) in.nextDouble()];
for (int i = 0; in.hasNextDouble(); i++) {
arr[i] = in.nextDouble();
}
} catch (FileNotFoundException e) {
file = new File("investments.txt");
System.out.print("File not found.\nPlease enter the correct path if needed.");
file = new File(in.nextLine());
}
in.close();
}
}
【问题讨论】:
-
请将您的问题缩小到您遇到问题的特定代码部分
-
我已将我的问题缩小到一个,我真诚地道歉,因为这个地方到处都是。