0
int[] number = {10, 20, 30, 40, 50};
for (int numb : numb) {

System.out.print(numb);


System.out.print(",");

}

need to resolve this in this kind of form

10,20,30,40,50

without the last character that is used

0

3 Answers 3

1

Yes. The easiest way would be a traditional for loop;

int[] number = {10, 20, 30, 40, 50}; 

for (int i = 0; i < number.length; i++) {
    if (i != 0) {
        System.out.print(",");
    }
    System.out.print(number[i]);
}

You might also use a StringJoiner or stream concatenation. But that would be more complicated than just using a regular for loop as above.

Sign up to request clarification or add additional context in comments.

1 Comment

it works thnx a lot
1

Build that string using a StringJoiner:

int[] number = {10, 20, 30, 40, 50};

StringJoiner joiner = new StringJoiner(",");
for (int numb : number)
    joiner.add(String.valueOf(numb));
String s = joiner.toString();

System.out.println(s); // prints: 10,20,30,40,50

1 Comment

Thank you im still new with java so StringJoiner its still new for me but it works amazing thnx
0

There are a few ways you could handle it.

You could use a "manual" for loop:

for (int i = 0; i < number; ++i) {...

... and then treat the case of when i + 1 == number.length as a special case.

You could also use IntStream, map that to a Stream using mapToObj, and then collect that stream using Collectors.joining(","):

String s = Stream.of(number)
  .mapToObject(Integer::toString)
  .collect(Collectors.joining(","));
System.out.print(s);

But the easiest way is probably to use Arrays.toString(int[]). That will produce a string with a space after each comma, but you can then do replaceAll(" ", "") to remove that.

1 Comment

Hmm trying to figure what you mean cuz im still knew with java can u write full code ?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.