删除逗号数字列表的结尾

时间:2016-10-21 09:39:37

标签: java

问题是打印出具有偶数索引的实际位置的元素,从1开始,它们的总和采用以下格式。例如, 如果元素的数量是6并且元素是 10,20,30,40,100和200,输出为

20, 40, 200
260

其中第二行输出表示偶数索引的总和,但我得到输出为

20, 40, 200
260

我怎样才能在最后摆脱逗号?

import java.util.*;

class Main {
    public static void main(String args[]) {
        int n, i, sum = 0;
        Scanner input = new Scanner(System.in);
        n = input.nextInt();
        int[] data = new int[n];
        for (i = 0; i < n; i++) {
            data[i] = input.nextInt();
        }
        for (i = 0; i < n; i++) {
            if ((i + 1) % 2 == 0) {
                System.out.print(data[i] + ",");
                sum += data[i];
            }
        }
        System.out.print("\n");
        System.out.println(sum);
    }
}

4 个答案:

答案 0 :(得分:3)

在这种情况下,我使用一个简单的技巧:

String SEPARATOR = "";
for(i = 0; i < n; i++) {
    data[i] = input.nextInt();
}
for(i = 0; i < n; i++) {
    if((i + 1) % 2 == 0) {
        System.out.print(SEPARATOR + data[i]);
        sum += data[i];
        SEPARATOR = ",";
    }
}

答案 1 :(得分:1)

您也可以使用三元运算符来执行此操作

for (int i = 0; i < n; i++) {
    if ((i + 1) % 2 == 0) {
        System.out.print(data[i] + i != n-1 ? "," : "");
        sum += data[i];
    }
}

答案 2 :(得分:1)

这是另一种解决方案:

// create Scanner in try-with-resources block so it gets closed at the end
try (Scanner input = new Scanner(System.in)) {
    int size = input.nextInt();
    int sum = 0;
    StringBuilder sb = new StringBuilder();

    for (int i = 0; i < size / 2; i++) {
        // read and discard even index (odd position)
        input.nextInt();
        int value = input.nextInt();
        sb.append(value).append(",");
        sum += value;
    }

    // remove last separator
    sb.deleteCharAt(sb.length() - 1);

    // if the size is odd, read and discard one more number
    if (size % 2 == 1) {
        input.nextInt();
    }
    System.out.printf("%s%n%s", sb, sum);
}

答案 3 :(得分:0)

以下是使用流的Java 8解决方案:

import java.io.*;
import java.util.*;

public class Adder {

    public static void main(String[] args) throws IOException {
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        StringJoiner numbers = new StringJoiner(",");
        final boolean[] flipFlop = new boolean[]{true};
        int size = Integer.parseInt(in.readLine());
        int sum = in.lines()
                .limit(size)
                .mapToInt(Integer::parseInt)
                .filter(i -> {
                    flipFlop[0] = !flipFlop[0];
                    return flipFlop[0];
                })
                .peek(i -> numbers.add(String.valueOf(i)))
                .sum();
        System.out.println(numbers);
        System.out.println(sum);
    }
}