在这里,我希望stringbuilder附加每个计算的结果。
但它的格式不对。
在代码中,我试图找到两个数字的所有逗号因子,并得到第k个值。但我的结果并没有达到预期的格式。

Expected Correct Output
4
1
No candy today

我得到的是:-
4

4
1

4
1

No candy today

我需要使用StringBuilder来快速处理输出。而不是每次我只需要调用一次系统。
import java.util.*;

class TestClass {
    public static void main(String args[] ) throws Exception {
        StringBuilder sb = new StringBuilder();
        Scanner scan = new Scanner(System.in);
        int D = scan.nextInt();
        int x = 0, y = 0, k = 0;
        List<Integer> commonDivisor = new ArrayList<Integer>();
        while(D-->0){
            commonDivisor.clear();
            x = scan.nextInt();
            y = scan.nextInt();
            k = scan.nextInt();
            k = k - 1;

            commonDivisor = getCommonDivisor(x, y);
            Collections.reverse(commonDivisor);
            if(k >= (commonDivisor.size())){
              sb.append("\nNo candy today");
            }else if(k <= (commonDivisor.size() - 1)){
                 sb.append(commonDivisor.get(k) + "\n");
            }
            System.out.println(sb);
        }
    }

    public static List<Integer> getCommonDivisor(int num1, int num2) {

    List<Integer> list = new ArrayList<Integer>();

    int min = minimum(num1, num2);

    for(int i = 1; i <= min / 2; i++) {
        if (num1 % i == 0 && num2 % i == 0) {
            list.add(i);
        }
    }

    if (num1 % min == 0 && num2 % min == 0) {
        list.add(min);
    }

    return list;
  }

  public static int minimum(int num1, int num2) {
    return num1 <= num2 ? num1 : num2;
  }

}

最佳答案

在每个循环迭代中都会打印字符串生成器,因此会打印所有步骤由于您希望避免在循环内打印,而是构建一个在最后打印的字符串,因此您应该将print语句移到循环外:

while(D-->0){
    commonDivisor.clear();
    x = scan.nextInt();
    y = scan.nextInt();
    k = scan.nextInt();
    k = k - 1;

    commonDivisor = getCommonDivisor(x, y);
    Collections.reverse(commonDivisor);
    if (k >= commonDivisor.size()) {
       sb.append("\nNo candy today");
    } else if (k <= (commonDivisor.size() - 1)){
       sb.append(commonDivisor.get(k) + "\n");
    }
}
System.out.println(sb);

08-16 22:40