My class project is to prompt the user for a file, that file name they input must be correct, once file is established, the first line of the file is the size of the array. Then, I have to assign each value, line by line, to the array.
Quick note** We haven't learned about buffered reader yet so I can't use that. I also can't use ArrayList, also haven't covered that yet.
Question: How do I make sure the file name they input is right? So far in class we've used while loops to check, but I'm wondering if there's a better way. I need the user to enter "investments.txt" otherwise I need to prompt them again and again. Also any points on improving existing code is very appreciated, I'm very new to this.
Code so far:
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();
}
}