当用户在输入中输入特定字符串时,如何中断程序

5

我希望让用户输入一些字符串,程序将接受控制台输入,直到用户键入“/done”为止。以下是它的工作原理:

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

  2. 用户输入:hello eclipse。

hi test blah blah

bla 456 testmore /done

只要用户在任何大小的字符串中输入/done,程序就会停止。如果您按“enter”键,程序不会结束。它只有在键入/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语句中的布尔值为false,程序就会继续执行。对于我的程序来说,程序会不断接收输入,直到用户输入/done,因此布尔值一直为false,直到字符串/done被输入为止。根据上述逻辑,当输入等于"/done"时,程序就会退出。

你有什么想法,是我做错了什么吗?


听起来你想要检查输入是否包含“/done”,而不是输入等于“/done”。 - John3136
无论使用者是否输入 /done 或它是一个更大字符串的一部分。 - Arun P Johny
你是不是真的要在独立的一行中输入“/done”? - PM 77-1
约翰 - 是的,你说得对,包含会比等于更好用。你会把它放在do-while循环的while里面吗??.. 阿伦 - 用户必须在字符串输入中一次性输入/done。不是单独一行 - 它可以是单独一行,但这并非必要。只需要"/done"在一起即可。 - sega_one
即使您调用了 contains,这意味着在用户按下回车键之前,您的程序不会中断。因此,我可以输入“blah blah /done blah blah<enter>”,这是您想要的吗? - Catchwa
我忘了提到那一部分。如果您在字符串中键入/done后按下回车键,则程序将终止。如果您在字符串/行中没有输入/done,只需在Eclipse控制台上移动到新行并在新行上继续用户字符串输入即可。希望这能稍微澄清一下。 - sega_one
3个回答

0

我认为这会很好地工作

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..");

0
         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;
            }
        }

0
你差不多就成功了,但是你需要使用contains而不是equals
Scanner scanner = new Scanner(System.in);
String input = "";
System.out.println("Enter your string: ");

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

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接