【问题标题】:How to remove Trailing White space in Queue/Priority Queue JAVA如何删除队列/优先队列 JAVA 中的尾随空格
【发布时间】:2020-04-15 18:59:36
【问题描述】:
public class StreamingIntegers {
    public static void main(String[] args) {
        Scanner scanin = new Scanner(System.in);
        PriorityQueue<Integer> sorted_num = new PriorityQueue<>();
        while (true) {
            String numbers = scanin.nextLine();
            if (numbers.equals("END")) {
                break;
            } else {
                String[] tokens = numbers.split(" ");
                for (String token : tokens) {
                    sorted_num.add(Integer.parseInt(token));
                }
            }
        }
        while (!sorted_num.isEmpty()) {
            System.out.print(sorted_num.remove() + " ");
        }
        scanin.close();
    }
}  

我怎样才能去掉最后的那个小空白?

【问题讨论】:

  • 请使用文字而不是图片。输出可以粘贴到问题中并像代码一样格式化。
  • 习惯上接受你最喜欢的答案

标签: java queue


【解决方案1】:

在第一次拉动之后,我会切换到将空间放在前面:

System.out.print(sorted_num.remove());
while (!sorted_num.isEmpty()) {
    System.out.print(" " + sorted_num.remove());
}

这不需要在每一行进行条件检查

如果你有可能得到一个空集合,你保护它:

if (sorted_num.isEmpty()) {
    System.out.print("Nothing to sort here!");
} else {
    System.out.print(sorted_num.remove());
    while (!sorted_num.isEmpty()) {
        System.out.print(" " + sorted_num.remove());
    }
}

希望有帮助

【讨论】:

    【解决方案2】:

    在最后的while 循环中,检查queue 的大小,如果它包含多个项目,则仅附加空格,如下所示:

    System.out.print((sorted_num.size()==1)?sorted_num.remove():sorted_num.remove()+" "); 
    

    【讨论】:

      【解决方案3】:

      另一种方法是使用最初为空字符串的前缀,并在循环中设置为空格:

      String prefix = "";
      while (!sorted_num.isEmpty()) {
          System.out.print(prefix + sorted_num.remove());
          prefix = " ";
      }
      

      【讨论】:

        猜你喜欢
        • 2013-02-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-03-19
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多