0

I have a file with content like this:

123,412

345,634

124,645

I want to get just the numbers before the commas in each row and add them to my arrayList. Why does my code only add the first number (123) correctly but doesn't continue on to add the rest?

try {
            File input = new File(filename);
            in = new Scanner(input);
            in.useDelimiter(",");

            while(in.hasNextLine()) {
                someArrayList.add(Integer.parseInt(in.next()));
            }
skaffman
  • 398,947
  • 96
  • 818
  • 769
AlldaRage
  • 121
  • 1
  • 1
  • 8

3 Answers3

0

If you only want the numerals before the comma, then just split the whole line on that. There's no need to use a delimiter for this.

Scanner input = new Scanner(new File(filename));
while(input.hasNextLine()) {
    String firstThreeDigits = input.nextLine().split(",")[0]
    someArrayList.add(Integer.parseInt(firstThreeDigits));
} 
Makoto
  • 104,088
  • 27
  • 192
  • 230
  • This works! Could you tell me why there is a [0] after the split statement? Also, how would you do this for numbers after the comma? – AlldaRage Mar 10 '15 at 04:39
  • `split` is returning an array of strings. `[0]` is the first element. If you want the second element, you'd have to store the line into a temporary string, then split it, and index into it by `[1]`. – Makoto Mar 10 '15 at 04:40
0

There are 2 mistakes here:

  • in.hasNextLine() - This is checking to see if there is another line in the input of this scanner
  • in.useDelimiter(","); - Using this delimiter will only work with commas if you continually call

Assuming that your input file is line by line, you could change both of the above to this:

File input = new File(filename);
in = new Scanner(input);
in.useDelimiter(",|\n");

while (in.hasNext()) {
    someArrayList.add(Integer.parseInt(in.next()));
}

I think a better way would just be to use readLine, and then String.split the resulting line.

mkobit
  • 43,979
  • 12
  • 156
  • 150
  • when I try it this way I'm getting: java.lang.NumberFormatException: For input string: "412 ". There is a new line after 412, that last quotation mark is on the next line. – AlldaRage Mar 10 '15 at 04:35
  • @AlldaRage you can change it to be `\\s+` instead of `\n` or call `String#trim()` on each value from `next()`. – Obicere Mar 10 '15 at 04:50
0

Here I am using nextLine to consume the line, and then splitting using regex ,

try {
        File input = new File(filename);
        in = new Scanner(input);
        while(in.hasNextLine()) {
         someArrayList.add(
       Integer.parseInt(in.nextLine().split(",")[0].replace("\\s+", "")));
  }

Take the line, split using ",", and get the first element, and replace all white space with nothing

EDToaster
  • 3,160
  • 3
  • 16
  • 25