首页 > 解决方案 > 输入某行后如何停止扫描?

问题描述

我想构建一个只停止扫描字符串的程序,直到我在控制台中输入“0”之后,我该怎么做?

我假设我可以使用 do while 循环,但我不知道在 while() 条件中放入什么。

    Scanner scan = new Scanner(System.in);

    do {

        String line = scan.nextLine(); 

        //do stuff

    } while(); //what do i put in here to stop scanning after i input "0"

在此先感谢,总的来说,我是 Java 和 OOP 的新手。

标签: javaloopsinput

解决方案


您可以使用 while 循环代替 do-while 循环。定义一个将在 while 循环内初始化的字符串。在每次迭代中,我们将 String 分配给 Scanner#nextLine 并检查该行是否不等于 0。如果是,则 while 循环会阻止迭代。

        Scanner scan = new Scanner(System.in);

        String line;

        while (!(line = scan.nextLine()).equals("0")) {
            System.out.println("line: " + line);
        }

推荐阅读