1 Replies - 365 Views - Last Post: 27 April 2011 - 11:35 AM Rate Topic: -----

#1 wales321  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 3
  • Joined: 27-April 11

Read text from a file and hold in an array

Posted 27 April 2011 - 09:51 AM

Hi Im trying to read lines from an external file and hold them in an array for future use using java.
I can read the file and print its contents but im not sure on the next step to hold the info in the array.

The information in the file looks similar to this
00001 1 3 2
00002 3 2 1

With first number is the number of a ballot paper and the next three numbers are ranks of three candidates by preference.

Any help much appreciated
Is This A Good Question/Topic? 0
  • +

Replies To: Read text from a file and hold in an array

#2 g00se  Icon User is online

  • D.I.C Lover
  • member icon

Reputation: 2735
  • View blog
  • Posts: 11,523
  • Joined: 20-September 08

Re: Read text from a file and hold in an array

Posted 27 April 2011 - 11:35 AM

An array is not a good candidate (excuse the pun)

It's not growable or shrinkable and unless you know exactly how many candidates you have, your allocation will be messy.

Much better to use a List of type Candidate. e.g

List<Candidate> candidates = new ArrayList<Candidate>();
Scanner in = new Scanner(new File("candidates.txt"));
while(in.hasNextLine()) {
    Candidate c = new Candidate(in.nextLine().split("\\s+"));
    candidates.add(c);
}
in.close();



This post has been edited by g00se: 27 April 2011 - 11:36 AM

Was This Post Helpful? 0
  • +
  • -

Page 1 of 1