【问题标题】:break program when user enters specific string into input当用户在输入中输入特定字符串时中断程序
【发布时间】:2013-03-23 04:02:13
【问题描述】:

我想让它让用户输入一些字符串,并且程序接受控制台输入,直到用户输入“/done”..所以它是这样工作的:

  1. 打印给用户:输入您的字符串

  2. 用户输入:你好 eclipse。

你好测试等等等等

布拉 456 测试更多/完成

只要用户在任何大小的任何字符串中输入 /done,程序就会中断。如果您按“回车”键,程序不会结束。它只会在你输入 /done 时结束。到目前为止我是如何设置我的程序的:

Scanner 123 = new Scanner(System.in);
string input = "";
System.out.println("Enter your string: ");

do {
    input = 123.nextLine();
    System.out.print("Rest of program here..");
}

while (!input.equals("/done"));

我尝试在 while 循环下放置类似下面的内容,但我认为我做得不对。

while (!input.equals("/done"));
    if input.equals("/done");
    break;
}

我知道,对于 do-while 循环,只要 while 中的布尔值为假,它就会继续。所以对于我的程序,程序接受输入,直到用户输入 /done 所以布尔值是假的,直到输入字符串 /done 。然后根据上面的逻辑,只要输入等于“/done”,程序就会中断

关于我做错了什么有什么想法吗?

【问题讨论】:

  • 听起来你想检查是否输入contains "/done" 而不是输入equals "/done"。
  • 使用类型是/done还是更大字符串的一部分
  • 你真的在自己的行上输入“/done”吗?
  • John - 是的,你是对的,包含会起作用而不是等于。你会把它放在 do-while 循环的 while 中吗? .. Arun - 用户必须在字符串输入中一次输入 /done。不在它自己的线上 - 它可以在它自己的线上,但没有必要。只需要一起“/完成”
  • 即使你调用contains 这意味着你的程序在用户按下回车键之前不会中断。所以我可以输入“blah blah /done blah blah”这就是你想要的吗?

标签: java string break do-while


【解决方案1】:

我认为这会很好用

Scanner scanner = new Scanner(System.in);
    String input = "";
    System.out.println("Enter your string: ");
        do {
        input = scanner.nextLine();
    } while (!input.contains("/done"));
    System.out.print("Rest of program here..");

【讨论】:

    【解决方案2】:
             Scanner s=new Scanner(System.in);
             String input = "";
             String[] parts;
             System.out.println("Enter your string: ");
             while (true){
                 input=s.nextLine();
                if (input.contains("/done")){
                parts=input.split("/done");
                //Use parts[0] to do any processing you want with the part of the string entered before /done in that line
                    break;
                }
            }
    

    【讨论】:

      猜你喜欢
      • 2019-10-12
      • 1970-01-01
      • 1970-01-01
      • 2021-08-25
      • 1970-01-01
      • 2022-01-05
      • 2017-09-11
      • 2020-08-10
      • 1970-01-01
      相关资源
      最近更新 更多