I keep running into this error when compiling this code here:
TryTryAgain.java:52: error: cannot find symbol if (file.hasNextInt()) { ^ symbol: variable file location: class TryTryAgain
It's not picking up the file symbol I defined in the try-catch block within that do-while loop while compiling. I'm not really sure how to fix this as it has to be in there or else I wouldn't be able to throw the exception and repeat until a valid file name is given.
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.NoSuchElementException;
import java.io.IOException;
import java.util.InputMismatchException;
public class TryTryAgain {
public static void main(String[] args) {
Scanner userInp = new Scanner(System.in);
System.out.print("Please enter the name of the file: ");
String userFile = userInp.next();
boolean fileAccepted = false;
do {
try {
Scanner file = new Scanner(new File(userFile));
fileAccepted = true;
} catch (FileNotFoundException e) {
System.out.println(userFile + " (The system cannot find the file specified)");
System.out.print("Please enter a valid file name: ");
userFile = userInp.next();
}
} while (fileAccepted == false);
int currentHighest = 0;
int currentLowest = 2147483647;
int totalOf = 0;
double totalNums = 0.0;
int currentNum;
//Making these to make the output look like the example ones
String total = "Total";
String min = "Min";
String max = "Max";
String average = "Average";
do {
if (file.hasNextInt()) {
totalNums++;
currentNum = file.nextInt();
totalOf += currentNum;
if (currentHighest < currentNum) {
currentHighest = currentNum;
}
if (currentLowest > currentNum) {
currentLowest = currentNum;
}
} else if (file.hasNextLine()) {
System.out.println("Skipping over invalid input: " + file.nextLine());
} else if (file.hasNextDouble()) {
System.out.println("Skipping over invalid input: " + file.nextDouble());
}
} while (file.hasNextInt() || file.hasNextLine() || file.hasNextDouble());
file.close();
if (totalNums > 0) {
double averageVal = (totalOf / totalNums);
System.out.printf("%7s: %d", total, totalOf);
System.out.printf("%7s: %d", min, currentLowest);
System.out.printf("%7s: %d", max, currentHighest);
System.out.printf("%7s: %d", average, averageVal);
} else {
System.out.println("No valid data found. No stats available.");
}
} //end main
}