• Post Reply Bookmark Topic Watch Topic
  • New Topic

How to read from a text file and placing three different values in an array?  RSS feed

 
George Avilez
Ranch Hand
Posts: 60
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I don't know how to read from a text file, well at least something this advanced. My text file contains this:

Snoopy // Dog name
13 // Dog age
39 // Dog weight
Jill // Same pattern
6
46


I'm trying to add the name age and weight into an array. I think the only problem I have is that the file will change once the user chooses to input anything, so I don't know how to loop them if I don't know how much info is in the file. The problem starts at line 66 (if user chooses to read off of text file), for now it's a while loop only because thats the only example I found in the text book. I'd like to use a for loop like at line 37. Can anybody help on what I can do to make this code easier?

 
Campbell Ritchie
Marshal
Posts: 56540
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Parallel arrays? A very bad idea. What you actually want is a Dog class which you can create an array of.
The easiest way to read a text file has, since Java5, probably been using a Scanner. Just beware of nextLine, which can do what you don't expect if called after anything other than nextLine.
Forget the GUI app altogether, and create a program which runs at the command line. You will find an example here. The Exception handling in that example is pretty awful. You can pass a File object to the Scanner's constructor, in which case you only need to handle a FileNotFoundException. You can use try with resources in Java7, which gets you out of having to use a finally to close the File.
Once you have got that working, you can put the GUI on top of it.
 
Campbell Ritchie
Marshal
Posts: 56540
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sorry for confusion about GUIs; I thought you had a GUI, so ignore anything about GUIs.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!