Results 1 to 3 of 3
- 11-29-2010, 08:01 PM #1
Member
- Join Date
- Nov 2010
- Posts
- 17
- Rep Power
- 0
Trouble with Try Catch blocks and file reading.
Hello there,
I had to improve this code in order for it to compile correctly and run in a fault tolerant way. I need my code to ask the user to enter a file to read from. If the file they enter isn't found, I need to repeatedly ask the user to re-enter a file name. Once a file is found, it should read in each line of the file and store them in an array. However, if a value is not an integer, it should be ignored and not stored in the array. Finally, we must double the size of the array each time the number of integers in the file is larger than the current size of the array. I am only worried about the first part for now (repeating the question as many times as needed).
Here is my code..
Java Code:import java.util.*; import java.io.*; public class lab10 { public static void main(String [] args) { Scanner inScan, fScan = null; String fName; String nextItem; int nextInt = 0; int i = 0; int [] A = new int[5]; do { try { inScan = new Scanner(System.in); System.out.println("Please enter the file to read from: "); fName = inScan.nextLine(); fScan = new Scanner(new File(fName)); } catch (Exception bad) { fName = null; } // not sure what to compare fName to in order to have the question // above repeat as many times as needed if the file the user enters // is not valid } while (fName.equals()); 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] + " "); } } }
- 11-29-2010, 08:54 PM #2
Why not use "while (!fName.exists());"?
EDIT: Er, sorry. Create a File object from fName, then check if it exists using .exists().Last edited by Zack; 11-29-2010 at 09:06 PM.
- 11-30-2010, 02:11 AM #3
Member
- Join Date
- Nov 2010
- Posts
- 17
- Rep Power
- 0
Similar Threads
-
Having trouble reading external txt file to an array
By Metastar in forum New To JavaReplies: 18Last Post: 07-22-2010, 12:29 AM -
App that blocks selected web pages.
By lolaika in forum Advanced JavaReplies: 3Last Post: 06-11-2010, 05:43 PM -
Java Blocks??
By abimaran in forum New To JavaReplies: 24Last Post: 11-07-2009, 04:22 PM -
Blocks Language 0.1
By JavaBean in forum Java SoftwareReplies: 0Last Post: 09-23-2007, 12:21 AM -
Task Blocks 0.5
By johnt in forum Java SoftwareReplies: 0Last Post: 08-08-2007, 09:43 PM
Bookmarks