简体   繁体   中英

How to remove trailing comma output?

I'm asking the user to input an integer, and printing out even values within the range of that integer. Currently when I execute the code, it adds a comma after the final value (ex: "2, 4, 6,"). Is there a way that will remove the comma in the last number?

Here's my code!

import java.util.Scanner;

public class MyClass {
    public static void main(String args[]) {
        int integers;
        int sum = 0;

        System.out.println("Please input a positive integer: ");
        Scanner myList = new Scanner(System.in);
        integers = myList.nextInt();

        if (integers <= 0) {
            System.out.println("Invalid Input!!!");
        }
        else {
            System.out.println("Even number(s): ");

            for (int i = 1; i <= integers; i++) {
                if (i % 2 == 0) {
                    System.out.print(i + ", ");
                    sum = sum + i;
                }
            }
        }
    }
}

Just check what the value of i is. If it is the last iteration then do not print it.

System.out.print(i);
if (i != integers) {
    System.out.print(", "); 
}

I suggest adding a test before your current single print statement for i not equal to 2 (since that is the first value you print all subsequent values should have a comma). Also, I suggest you start your loop at 2 and increment by 2 (then you need no modulo two test). Like,

for (int i = 2; i <= integers; i += 2) {
    if (i != 2) {
        System.out.print(", ");
    }
    System.out.print(i);
    sum += i;
}

Alternatively, you could use a StringJoiner like

StringJoiner sj = new StringJoiner(", ");
for (int i = 2; i <= integers; i += 2) {
    sj.add(String.valueOf(i));
    sum += i;
}
System.out.println(sj);

Alternative solution using streams and String.join:

List<String> evenInts = IntStream.range(0, integers)
                .filter(i -> i % 2 == 0)
                .mapToObj(Integer::toString)
                .collect(Collectors.toList());
System.out.println(String.join(", ", evenInts));

Also possible:

System.out.println(IntStream.range(0, integers)
                .filter(i -> i % 2 == 0)
                .mapToObj(Integer::toString)
                .collect(Collectors.joining(", ")));

You can easily do it using below solution

for (int i = 1; i <= integers; i++) {
                    if (i % 2 == 0) {
                        if(i==2)
                       {
                         System.out.print(i);
                         continue;
                         }
                        System.out.print(", "+i);
                        sum = sum + i;
                    }
                }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM