dfburke
dfburke

Reputation: 13

reading string of ints and adding ints to an array

So I have a String that was given to me. I have eliminated all non integer characters, except for whitespace. Each line the amount of integer varies, some lines I will have one, sometimes I have two or even three. I now need to read in each integer and add them to an array list accordingly. Currently this is what I have:

while(fileScanner.hasNextLine()){
        fileScanner.nextLine();
        line=lineReplacer.nextLine();
        String line2=line.replaceAll("[a-z]","").replaceAll("[A-Z]","").replaceAll(": ","").replaceAll(" ","").replaceAll(", ", " ");
        specs.add(Integer.parseInt(line2));
    }

I am stuck on how to add in each int, without getting an error, without knowing how many ints are the line I currently have.

Edit: Expected values would be things such as, 2 2 2, or 12 14 11, or just 10, or 29 30. The ints must stay separated because they need to be added to an array. The only limitation on input is that it isn't more than three ints.

Upvotes: 1

Views: 54

Answers (3)

Henry
Henry

Reputation: 43738

nextInt works fine in this situation, it skips the white space between the integers. Try for example:

import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        Scanner fileScanner = new Scanner("1 2 23 4\n3");
        while (fileScanner.hasNextInt()) {
            System.out.println(fileScanner.nextInt());
        }
    }

}

This gives output:

1
2
23
4
3

Upvotes: 0

Bhushan
Bhushan

Reputation: 6181

Try this:

String line="Hello 12 hi 458 h20 Bye 8";
String line2 = line.replaceAll("\\D+","");
System.out.println(line2);

Output:

12458208

You can add all values to list like:

for(int i=0;i<line2.length();i++)
{
    specs.add(Integer.parseInt(line2.charAt(i)+""));
}

Upvotes: 2

Ankur Shanbhag
Ankur Shanbhag

Reputation: 7804

Try this:

    String line = "ABC 1000,snsdf 987";
    Pattern pattern = Pattern.compile("\\d+");
    Matcher matcher = pattern.matcher(line);
    List<Integer> list = new ArrayList<Integer>();
    while (matcher.find()) {
        String match = matcher.group();
        list.add(Integer.parseInt(match));
    }

You can convert the list to an array if needed:

    Integer[] array = new Integer[list.size()];
    array =  list.toArray(array);

Upvotes: 1

Related Questions