-2

I'm reading from a file using Scanner, and the text contains the following.

[8, 3, 8, 2, 3, 4, 4, 4, 5, 8]

This was originally an integer Array that I had to convert to a String to be able to write in the file. Now, I need to be able to read the file back into java, but I need to be able to add the individual numbers together, so I need to get this String back into an array. Any help? Here's what I have:

File f = new File("testfile.txt");  
try{
    FileWriter fw = new FileWriter(f); 
    fw.write(Arrays.toString(array1)); 
    fw.close(); 
} catch(Exception ex){
    //Exception Ignored
}

Scanner file = new Scanner(f);       
System.out.println(file.nextLine());

This prints out the list of numbers, but in a string. I need to access the integers in an array in order to add them up. This is my first time posting, let me know if I messed anything up.

Sully
  • 14,672
  • 5
  • 54
  • 79
Shambaree
  • 35
  • 4

3 Answers3

4

You can use String#substring to remove the square brackets, String#split to split the String into an array, String#trim to remove the whitespace, and Integer#parseInt to convert the Strings into int values.

In Java 8 you can use the Stream API for this:

int[] values = Arrays.stream(string.substring(1, string.length() - 1)
                     .split(","))
                     .mapToInt(string -> Integer.parseInt(string.trim()))
                     .toArray();

For summing it, you can use the IntStream#sum method instead of converting it to an array at the end.

2

You don't need to read the String back in an Array, just use Regex

public static void main(String[] args) throws Exception {
    String data = "[8, 3, 8, 2, 3, 4, 41, 4, 5, 8]";
    // The "\\d+" gets the digits out of the String
    Matcher matcher = Pattern.compile("\\d+").matcher(data);

    int sum = 0;
    while(matcher.find()) {
        sum += Integer.parseInt(matcher.group());
    }

    System.out.println(sum);
}

Results:

86

Shar1er80
  • 9,001
  • 2
  • 20
  • 29
0
List<Integer> ints = new ArrayList<>();
String original = "[8, 3, 8, 2, 3, 4, 4, 4, 5, 8]";
String[] splitted = original.replaceAll("[\\[\\] ]", "").split(",");
for(String s : splitted) {
    ints.add(Integer.valueOf(s));
}
Stewart
  • 17,616
  • 8
  • 52
  • 80
  • 3
    Mind spaces and square brackets. – Egor Jun 03 '15 at 16:22
  • But the concept is valid. For this, a downvote? – Stewart Jun 03 '15 at 16:23
  • 2
    @Stewart, It wasn't actually me downvoting, but your answer is incomplete. While the concept is valid, you should at least describe the shortcomings of your solution, or better give a full solution. – Egor Jun 03 '15 at 16:25