Andy Andy - 19 days ago 6
Java Question

IOException Loop

I need help figuring out how to loop my

IOException
(in where I ask for a filename until a valid one is entered). I need a loop that somehow recognizes that an invalid file was entered and am unsure how to do this.

import java.util.*;
import java.io.*;
public class JavaGradedLab {
public static void main(String[] args) throws IOException {

Scanner inScan, fScan = null;
int [] A = new int[5];
inScan = new Scanner(System.in);
System.out.println("Please enter the file to read from: ");

try{
String fName = inScan.nextLine();
fScan = new Scanner(new File(fName));
}

catch (FileNotFoundException ex)
{
System.out.println("Your file is invalid -- please re-enter");
}

String nextItem;
int nextInt = 0;
int i = 0;

while (fScan.hasNextLine())
{
nextItem = fScan.nextLine();
nextInt = Integer.parseInt(nextItem);
A[i] = nextInt;
i++;
}

System.out.println("Here are your " + i + " items:");
for (int j = 0; j < i; j++)
{
System.out.println(A[j] + " ");
}
}
}

Answer

Well, there's sure to be someone explaining how to make your code better via best practices etc., but as a very basic answer which in itself can probably be improved (assuming that your code works when the input is valid):

while(true) {
    try{
        String fName = inScan.nextLine();
        fScan = new Scanner(new File(fName));
        break;
    }
    catch (FileNotFoundException ex)
    {
        System.out.println("Your file is invalid -- please re-enter");
    }
}
Comments