【问题标题】:Reading stdin results in an infinite loop in Intellj在 Intellij 中读取标准输入会导致无限循环
【发布时间】:2021-01-07 11:00:12
【问题描述】:

我在阅读 stdIn 时遇到问题。问题是,当使用 SDK Java 13 从 IntellJ 执行时,它永远不会停止。我的输入是:

0 1 2
0 2 4
1 3 4
1 2 2
3 2 1

我的代码是:

class Vertex {
    private int label;
    private boolean visited = false;

    public Vertex(int name) {
        this.label = name;
    }
    
    @Override
    public int hashCode() {
        return label;
    }
}

public class HelloWorld{

     public static void main(String []args){
        Scanner scan = new Scanner(System.in);
        HashSet<Vertex> h= new HashSet<>();
        while(scan.hasNext()){
            int s = scan.nextInt();
            System.out.println("s "+ s);
            h.add(new Vertex(s));
        }
        
        System.out.println("Its done");
     }
}

我真的不明白发生了什么。当我在在线 Java 编译器中运行它时,它可以工作,但不能在 Intellj 中运行,在线编译器使用 Java 1.8。

【问题讨论】:

  • 我不是 intellij 用户,但您的意思是您在 intellij 中有一个终端仿真器,当您将输入粘贴到其中时,它就挂在那里?
  • 发帖后请不要做太多修改。我正在尝试运行您的代码
  • scan.hasNext()System.in 上运行时将始终等待下一个输入,永远不会返回 false - 它永远不会“完成”。
  • 尝试 ctrl-D 或其他终端文件结束命令之一来表示流已完成
  • FedericoklezCulloca,这正是我所做的。在 intellij 中,你有一个终端模拟器。

标签: java intellij-idea stdin


【解决方案1】:

您可以稍微修改 while 循环。您可以插入一个单词来中断循环。在示例中为break。如果输入了数字,则可以创建新顶点,否则会显示帮助消息。

try (Scanner scan = new Scanner(System.in)) {
    HashSet<Vertex> h = new HashSet<>();

    while (!scan.hasNext("break")) {

        if (scan.hasNextInt()) {
            int s = scan.nextInt();
            System.out.println("s " + s);
            h.add(new Vertex(s));
        } else {
            System.out.printf(
                "You entered: \"%s\". Please enter a valid number or \"break\" if you want to end the loop.%n",
                scan.next());
        }
    }

    System.out.println("Its done");
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-12-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-04
    相关资源
    最近更新 更多