java - Java 代码中的结果格式不正确

标签 java string algorithm stringbuilder system.out

在这里,我希望 Stringbuilder 附加每次计算的结果。 但它的格式不正确。

在代码中,我试图找到两个数字的所有公因数并获得第 k 个值。但是我的结果没有以预期的格式出现。

Expected Correct Output
4
1
No candy today

我得到的是:-

4

4
1

4
1

No candy today

我需要使用 StringBuilder 来快速处理输出。而不是每次都调用 System.out 我只需要调用它一次。

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;
  }

}

最佳答案

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

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);

关于java - Java 代码中的结果格式不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30286880/

相关文章:

java - 如何实现 JTable 单元格更改的事件处理程序

使用函数将 long long int 转换为字符串,无需 sprintf

PHP处理大字符串

algorithm - 计算密集型算法

c++ - 代码理解问题

algorithm - 计算在基于瓦片的游戏中哪些瓦片被点亮 ("raytracing")

java - 使用 Java 8 流将 Map<File, File> 转换为 Map<File, List<File>>

java - 将组件添加到 JPanel 是否存在问题?

java - 如何获取当前选项卡的标题

java - 如何在 Java 中填充字符串?