Home > Software design >  how to remove the comma after the number 19
how to remove the comma after the number 19

Time:10-19

How do I remove the comma after the number 19?

class Main {
  public static void main(String[] args) {
    int numbers[] = {23, 79, 41, 68, 17, 39, 51, 75, 95, 19};
    System.out.print("Integer values: ");
    for(int i = 0; i < numbers.length; i  ){
      System.out.print(numbers[i]   ",");
      

    }
    int smallestNumber = numbers[0];
    for(int i = 0; i < numbers.length; i  ){
      if (numbers[i] < smallestNumber){
        smallestNumber = numbers[i];
      }  
  }
    System.out.println("\nSmallest integer: "   smallestNumber);

}
}

This is how it looks like after its run

Integer values: 23,79,41,68,17,39,51,75,95,19,
Smallest integer: 17

This is how I want it to look

Integer values: 23,79,41,68,17,39,51,75,95,19
Smallest integer: 17

CodePudding user response:

You can modify the loop

for(int i = 0; i < numbers.length - 1; i  ) {
  System.out.print(numbers[i]   ",");
}
System.out.print(numbers[numbers.length - 1]);

Or use streams

 Arrays.stream(numbers).collect(Collectors.joining(","));

CodePudding user response:

StringJoiner is used to construct a sequence of characters separated by a delimiter and optionally starting with a supplied prefix and ending with a supplied suffix. Here in this case we are using the delimiter as ,

int numbers[] = {23, 79, 41, 68, 17, 39, 51, 75, 95, 19};
StringJoiner stringJoiner = new StringJoiner(",");

System.out.print("Integer values: ");
for (int i = 0; i < numbers.length; i  ) {
   stringJoiner.add(String.valueOf(numbers[i]));
}

System.out.println(stringJoiner);

CodePudding user response:

Just to add-on:

You can also use streams to find the minimum integer from the given array:

int numbers[] = {23, 79, 41, 68, 17, 39, 51, 75, 95, 19};
        Optional<Integer> minNumber = Arrays.stream(numbers).boxed()
                                     .min(Comparator.naturalOrder());
        minNumber.ifPresent(System.out::println);

Output:

17

CodePudding user response:

Since the array is hard coded, you know the array will never be size 0. You can print the first element. Then have a loop that prints the rest of the elements each with a comma prepended.

    int numbers[] = {23, 79, 41, 68, 17, 39, 51, 75, 95, 19};
    
    System.out.print("Integer values: ");
    System.out.print(numbers[0]);
    for(int i = 1; i < numbers.length; i  ){
      System.out.print(","   numbers[i]);
    }

CodePudding user response:

int numbers[] = {23, 79, 41, 68, 17, 39, 51, 75, 95, 19};
System.out.print("Integer values: ");
for(int i = 0; i < numbers.length; i  ){
  if(i == numbers.length-1){
       System.out.print(numbers[i]);
       break;
  }
  System.out.print(numbers[i]   ",");

}
  • Related