Hello. I have a program that is supposed to read a .txt file, save the data in an array, then print out that data. I have a program that compiles, but when I run it, it does not print the first line of the .txt file, prints the second line, then does not print the third line, but stays in the run and freezes. Here's the .txt file which is named "inventory.txt" ...
Basketball 2 20.00
Baseball 3 5.00
Soccerball 5 20.00
...and the output should be...
Peter's Sport Store Inventory List
Item Units Price Total Price
Basketball 2 20.00 40.00
Baseball 3 5.00 15.00
Soccerball 5 20.00 100.00
Here is the driver program that I've come up with so far:
I'm really confused as to why the program only reads the second line, then refuses to loop and read the third one. Thanks for any help!
Basketball 2 20.00
Baseball 3 5.00
Soccerball 5 20.00
...and the output should be...
Peter's Sport Store Inventory List
Item Units Price Total Price
Basketball 2 20.00 40.00
Baseball 3 5.00 15.00
Soccerball 5 20.00 100.00
Here is the driver program that I've come up with so far:
Code:
import java.io.*; import javax.swing.*; import java.text.*; import java.util.StringTokenizer; public class Inventory { public static void main(String[] args) throws IOException { BufferedReader stdin = new BufferedReader(new InputStreamReader (System.in)); final int MAX = 500; InventoryItem[] items = new InventoryItem[MAX]; StringTokenizer tokenizer; String line, name, file = "inventory.txt"; int units, count = 0; double price; try { FileReader fr = new FileReader(file); BufferedReader inFile = new BufferedReader(fr); line = inFile.readLine(); while ((line = inFile.readLine()) != null) { tokenizer = new StringTokenizer(line); while (tokenizer.hasMoreElements()) { name = tokenizer.nextToken(); try { units = Integer.parseInt(tokenizer.nextToken()); price = Double.parseDouble(tokenizer.nextToken()); items[count++] = new InventoryItem(name, units, price); } catch (NumberFormatException exception) { System.out.println("Error in input. Line ignored:"); System.out.println(line); } line = inFile.readLine(); } } inFile.close(); for (int scan = 0; scan < count; scan++) System.out.println(items[scan]); } catch (FileNotFoundException exception){ System.out.println("The file " + file + " was not found."); } catch (IOException exception){ System.out.println(exception); } stdin.read(); } }
Comment