I am attempting to learn how to prompt users to enter a file name, rather than predefining it, so that Java can go through with the Scanner and read through it. I have written a program that does what I need it to do, but only when the file in question is predefined.
I have looked around the site for duplicate questions, and found a few, but the scope in which it was asked was a bit more advanced than where I am. Can anyone offer me a bit of guidance on how to prompt a user to enter the file he/she wants, as opposed to predefining it (as code below is set to).
Note - This was written assuming the files read in had integers < 0 and > 0, hence why the min/max functions were done in the way they were...simply trying to teach myself one step at a time.
import java.io.*;
import java.util.*;
public class ProcessNumbers {
public static void main(String[] args) throws FileNotFoundException {
Scanner input = new Scanner(new File("inputdata.txt"));
int max = 0;
int min = 0;
int sum = 0;
int count = 0;
double average = 0;
System.out.println("Enter file name: "); //currently a println for ease of reading via Run
while (input.hasNext()) {
if (input.hasNextInt()) {
int number = input.nextInt();
sum += number;
count++;
average = (double) (sum) / count;
if (number > max) {
max = number;
}
if (number < min) {
min = number;
}
} else {
input.next();
}
}
System.out.println("Maximum = " + max);
System.out.println("Minimum = " + min);
System.out.println("Sum = " + sum);
System.out.println("Count = " + count);
System.out.println("average = " + average);
}
}