1

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]
1
  • 1
    Move the location of the System.out.println(...) outside the loop? Commented May 13, 2016 at 2:10

2 Answers 2

2

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));
Sign up to request clarification or add additional context in comments.

1 Comment

wooow... I didn't realize it was in there and i spent 30 mins browsing the web before asking here. thanks a lot.
1

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]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.