Sher
Sher

Reputation: 121

Java String into Array

I converted a string to an array and made it into an integer array. I also multiplied all the values in the array by 3 and it works. My question is how do I make it so that the the output only shows [3,6,9,15] instead of what was shown in the block below.

public static void main(String[] args) {
    String arr = "1,2,3,5";

    String[] items = arr.split(",");

    int[] results = new int[items.length];

    for (int i = 0; i < items.length; i++) {
            results[i] = Integer.parseInt(items[i]);       
            results[i] *= 3;
            System.out.println(java.util.Arrays.toString(results));

    }


   }

OUTPUT: 
[3, 0, 0, 0]
[3, 6, 0, 0]
[3, 6, 9, 0]
[3, 6, 9, 15]

Upvotes: 1

Views: 89

Answers (2)

Elliott Frisch
Elliott Frisch

Reputation: 201447

In Java 8+ you could use a lambda and stream the tokens (and I'd add \\s* to support optional whitespace around the comma to the regular expression) and then use a pair of map functions. Something like,

String arr = "1,2,3,5";
int[] results = Stream.of(arr.split("\\s*,\\s*")).mapToInt(Integer::parseInt)
        .map(x -> x * 3).toArray();
System.out.println(Arrays.toString(results));

Output is (as requested)

[3, 6, 9, 15]

Upvotes: 1

Scary Wombat
Scary Wombat

Reputation: 44834

Move the printing to outside the loop

for (int i = 0; i < items.length; i++) {
        results[i] = Integer.parseInt(items[i]);       
        results[i] *= 3;
}

System.out.println(java.util.Arrays.toString(results));

Upvotes: 2

Related Questions