当用户将特定字符串输入到输入时,中断程序

问题描述 投票:4回答:2

我想这样做,以便用户输入一些字符串,程序接受控制台输入,直到用户键入“/ done”..所以这里是如何工作:

  1. 打印到用户:输入您的字符串
  2. 用户输入:hello eclipse。

嗨测试等等等等

bla 456 testmore / 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循环,只要boolean in while为false,它就会继续。所以对于我的程序,程序接受输入,直到用户输入/ done所以boolean为false,直到输入中的字符串/完成为止。然后根据上面的逻辑,一旦输入等于“/ done”,程序就会中断

关于我做错了什么的任何想法?

java string break do-while
2个回答
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
投票

我认为这样可以正常工作

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..");
© www.soinside.com 2019 - 2024. All rights reserved.