-4

From a text file that contains several lines, how only the first word of each line is read and stored in an array or a list? For example, the file is just one word per line. as below:

A , 5
B , 3
C , 5
D , 4
E , 3
. 
.
.

please help me

raha_gh
  • 21
  • 1
  • 4

2 Answers2

1

//global arraylist

ArrayList<String> aList=new ArrayList<String>();

loop through the file and read each line .. as you are reading ...

string line = br.readLine() ....

// line = "A,5"

string []words =line.split(',');

// words[]= {A,5};

aList.add(words[0]);

Or simple

aList.add(br.readLine.split(',')[0]);
Ace McCloud
  • 798
  • 9
  • 27
0

I am here to help you on adding that into an ArrayLists. I know I am a little late, but I'll give you my best. I would recommend creating a private String ArrayList class up above. So like

private ArrayLists<String> first;  

Start off by reading the line of the file by using a Scanner. Like this:

Scanner console = new Scanner(Name of the File);

By the way, I'm assuming you created a name for that file so the scanner can read it.

Next, you have that Scanner read each line of that file like this.

while(console.hasNextLine()) {

and inside of it, you create a String for that Scanner like this

        String z = console.nextLine();

and then you create a String Array inside and have it split by whatever you have in between, in your case, it's a Space. so like this.

String [] zip = z.split(" ")

Then, you add whatever is in that zip, with the first index which is zero. And there you have it.

first.add(zip[0]);

        }
    }

Sorry it's a little messy, Let me clear it up now.

 private ArrayLists<String> first; 
 Scanner console = new Scanner(Name of the File);
 while(console.hasNextLine()) 
 {
 String z = console.nextLine();
 String [] zip = z.split(" ")
 first.add(zip[0]);

     }
 }

Let me know if anything is flawed here. I tried my best.

Adan Vivero
  • 422
  • 12
  • 36