Output of odd array elements separated by commas Java

Please help me understand : there is a method called printOddNumbers that accepts an array and outputs only odd numbers from it, separated by commas, to the console. The end of the output should move the cursor to a new line.

Example input: [3,5,20,8,7,3,100]

Example output: 3,5,7,3

My output is: 3,5,7,3,

That is, I need to remove the last comma.

Please help me, how can I remove the comma at the end?

It also doesn't work for me this code is used if the array elements are negative. Please help me find the bug. Thank you in advance.

Link to the online compiler with the code:

Https://paiza.io/projects/OVNkb7xbg3IMP9liR15thg?language=java

public static void main(String[] args) {
    int[] strArray = new int[]{3, 5, 20, 8, 7, 3, 100};
    printOddNumbers(strArray);
}

public static void printOddNumbers(int[] arr) {
    StringBuilder stringBuilder = new StringBuilder();
    for (int i = 0; i < arr.length - 1; i++) {
        if (arr[i] % 2 == 1)
            if ((i == arr.length - 1)) {
                stringBuilder.append(arr[i]);
            } else {
                stringBuilder.append(arr[i] + ",");
            }
    }
    System.out.println(stringBuilder);
    stringBuilder.append(System.getProperty("line.separator"));
}

Output: 3,5,7,3,

Author: user4166, 2020-02-19

7 answers

public static void printOddNumbers(int[] arr) {
    StringBuilder stringBuilder = new StringBuilder();
    for (int value : arr) {
        if (value % 2 == 1) {
            stringBuilder.append(value + ",");
        }
    }
    System.out.println(stringBuilder.substring(0,stringBuilder.length()-1));
}

Or

public static void printOddNumbers(int[] arr) {
    StringBuilder stringBuilder = new StringBuilder();
    for (int value : arr) if (value % 2 == 1) stringBuilder.append(value + ",");
    stringBuilder.deleteCharAt(stringBuilder.length()-1);
    System.out.println(stringBuilder);
}
 0
Author: Jackson750, 2020-02-19 12:03:32

Please help me, how can I remove the comma at the end?

Why are you adding it?

stringBuilder.append(arr[i] + ",");

For each element, a comma is added at the end. There are three solutions here

  1. After the loop, remove the last comma from StringBuilder

    if (stringBuilder.length() > 0)
      stringBuilder.deleteCharAt(stringBuilder.length() - 1)
    
  2. Add a comma before the element for all but the first

    if (stringBuilder.length() > 0)
      stringBuilder.append(',');
    stringBuilder.append(arr[i]);
    
  3. Add the desired items to the list, and then call Arrays.toString(tmpList)

This code does not work if the array elements are negative

Because the remainder of dividing a negative odd number by 2 will be -1. So if the odd check is rewritten like this

if (arr[i] % 2 != 0)

Then the code will work with both positive and negative numbers

In addition, with such a cycle

for (int i = 0; i < arr.length - 1; i++) {

You will skip the last element of the array. The loop should be like this

for (int i = 0; i < arr.length; i++) {
 1
Author: Anton Shchyrov, 2020-02-19 12:04:39

There is an interesting StringJoiner class for such things.

Here is an example:

public static void main(String[] args) {
    StringJoiner joiner = new StringJoiner(",", "", "\r\n");
    int[] arr = {3,5,20,8,7,3,100};
    for (int e : arr) {
        if (e % 2 != 0)
            joiner.add(String.valueOf(e));
    }
    System.out.println(joiner.toString());
}
 1
Author: Sergey Semendyaev, 2020-02-19 14:45:28
string.substring(0,string.length() -1)
 0
Author: Olmicron, 2020-02-19 11:59:05

Your loop exit condition is incorrect

 i < arr.length - 1

The unit does not need to be subtracted, because of this, the last element of the array is not analyzed at all. You need to do this:

i < arr.length

This line is generally superfluous, since it essentially does nothing, and the line feed does System.out.println

stringBuilder.append(System.getProperty("line.separator"));

The comma condition is incorrect, as it will only work if you have the last element odd. It is more logical in this case to put a comma before the number, and not after it. For negative ones, take the module from the remainder. The result will be something like this:

public static void printOddNumbers(int[] arr) {
    StringBuilder stringBuilder = new StringBuilder();
    boolean first = true;
    for (int i = 0; i < arr.length; i++) {
        if (Math.abs(arr[i] % 2) == 1)
            if (first) {
                stringBuilder.append(arr[i]);
                first = false;
            } else {
                stringBuilder.append("," + arr[i]);
            }
    }
    System.out.println(stringBuilder);
}
 0
Author: iksuy, 2020-02-19 12:06:34

Well, the streams why no one offered

int[] strArray = new int[]{3, 5, 20, 8, 7, 3, 100};
String result = IntStream.of(strArray)
        .filter(i -> (i & 1) != 0)
        .mapToObj(String::valueOf)
        .collect(Collectors.joining(","));
System.out.println(result);

 0
Author: Andrew Bystrov, 2020-02-19 16:53:20

Method Stream.flatMap allows you to expand the current stream with additional elements:

public static void main(String[] args) {
    printOddNumbers(new int[]{3, 5, 20, 8, 7, 3, 100}); // 3,5,7,3
}

public static void printOddNumbers(int[] arr) {
    Arrays.stream(arr)
            // нечетные числа
            .filter(i -> i % 2 != 0)
            // число в виде строки
            .mapToObj(String::valueOf)
            // добавляем запятую перед
            // каждой строкой
            .flatMap(i -> Stream.of(",", i))
            // пропускаем первую запятую
            .skip(1)
            // выводим в одну строку
            .forEach(System.out::print);
    // перевод курсора
    // на новую строку
    System.out.println();
}
 0
Author: , 2020-12-07 03:42:22