944,191 Members | Top Members by Rank

Ad:
  • Java Discussion Thread
  • Unsolved
  • Views: 16901
  • Java RSS
May 4th, 2005
0

Reading an array from a file

Expand Post »
How do I initialize an array that has been called from a file? There will be 5 values in the array. So should my file "input.dat" have:
5 (number of values)
4 (value)
6 (value)
7 (value)
2 (value)
7 (value)


Example:
BufferedReader br = new BufferedReader(
new FileReader("input.dat"));


and I'm lost after that.

Thanks,
Bud
Similar Threads
Reputation Points: 10
Solved Threads: 0
Newbie Poster
Bud4java is offline Offline
13 posts
since Mar 2005
May 5th, 2005
0

Re: Reading an array from a file

Some progress has been made...

I've been able to create the text file with data, and create the array. The thing that I cannot get it to do is to use the first number in the file as the size of the array. The array in the text file is a set of scores, and there are 5 scores. The first number is supposed to set the size of the array, so the first number is 5, followed by the actual 5 values in the array.

Is this possible? If so, how would I setup the declaration/initialization statement?
Right now I have:

BufferedReader fr = new BufferedReader (new FileReader ("goals.txt"));int score [] = new int [5];
// read all scores from the files goals.txt
for (int i = 0 ; i < 5 ; i++)
{

goal [i] = Integer.parseInt(fr.readLine ());
}
// display the nine goals on the screen
System.out.print ("The goals are: ");
for (int i = 0 ; i < 5; i++)
{
if (i < 4)
// add a comma if not the last hole
System.out.print (score [i] + ", ");
else
// no comma and a prinln for the last output
System.out.println (score [i]);
} // end loop




The text file contains:
5
99
88
79
98
100

but it still wants to consider the "5" as part of the data in the array instead of it being the size of the array.

Any suggestions?


Thanks for your help & consideration,
Bud
Reputation Points: 10
Solved Threads: 0
Newbie Poster
Bud4java is offline Offline
13 posts
since Mar 2005
May 6th, 2005
0

Re: Reading an array from a file

take a long at java.io.ObjectOutput as this has already been created for you...

http://java.sun.com/j2se/1.5.0/docs/...ectOutput.html
no sense reinventing the wheel
Reputation Points: 13
Solved Threads: 4
Posting Whiz
paradox814 is offline Offline
351 posts
since Oct 2004

This thread is more than three months old

No one has posted to this discussion for at least three months. Please let old threads die and do not reply to them unless you feel you have something new and valuable to contribute that absolutely must be added to make the discussion complete. Otherwise, please start a new thread in this forum instead.
Message:
Previous Thread in Java Forum Timeline: problem
Next Thread in Java Forum Timeline: decrypting





About Us | Contact Us | Advertise | Acceptable Use Policy
Forum Index | Build Custom RSS Feed


Follow us on Twitter


© 2011 DaniWeb® LLC