【问题标题】:How to stop scanning after I input a certain line?输入某行后如何停止扫描?
【发布时间】:2020-03-20 12:09:15
【问题描述】:

我想构建一个只停止扫描字符串的程序,直到我在控制台中输入“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 的新手。

【问题讨论】:

标签: java loops input


【解决方案1】:

您可以使用 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);
        }

【讨论】:

  • nextLine() 仍然需要 0
  • 我认为他想输入输入直到 0 被按下,所以你的代码仍然让零输入,因为,nextLine() 将占用整行,不管你应用什么条件,请看我的回答
  • 呃,他说直到我输入 0 之后,这意味着在某些时候他希望输入 0。这将允许他处理该输入直到提供 0。跨度>
  • 我是不是听错了,还是没看懂,他没有举例,我按照我的理解回答了
  • 是的,我认为这是对问题的误解。
【解决方案2】:

您不必使用任何循环,正如您所说,您希望在默认情况下按下 0 时停止输入 nextLine() 当用户按下回车键时输入停止,因为它是分隔符,所以只需更改分隔符

Scanner scanner = new Scanner(System.in);
scanner.useDelimiter("0");   //regex
String s = scanner.next(); // no matter what user enters the s will contain the input before 0

【讨论】:

  • 用户说直到我停止扫描字符串所以暗示他们想要多个字符串值,这意味着需要某种类型的循环机制。不是单线。
猜你喜欢
  • 1970-01-01
  • 2020-08-26
  • 1970-01-01
  • 1970-01-01
  • 2012-01-04
  • 1970-01-01
  • 2017-03-20
  • 2016-03-13
相关资源
最近更新 更多