繁体   English   中英

如何检查 Java 中字符后的字符串

[英]How to check for strings after a character in Java

我试图做到这一点,以便用户在任何时候输入“在此处插入单词”,程序都会识别出这是一个无效的命令,并向用户发送一条消息,说“无效的命令类型。命令列表的帮助”。 我已经有我的活动命令工作,但我不确定如何在这里捕获无效命令是我的代码。

while (true) {

 String userInput = scan.nextLine();
 
 if (userInput.equals(".help")) {

 //print list of commands
 }

 else if (userInput.equals(".ping") {
 //print pong
 }

 //check for any String that starts with . but does not equal the previous commands and return an error message
}

您可以使用switch语句来处理未知命令:

while (true) {
    String userInput = scan.nextLine();

    switch(userInput) {
        case ".help":
            // print list of commands
            break;

        case ".ping":
            // print pong
            break;

        default:
            // print error message for unknown command
    }
}
while (true) { String userInput = scan.nextLine(); if (userInput.equals(".help")) { //print list of commands } else if (userInput.equals(".ping")) { //print pong } else if(userInput.startsWith(".")) { // applies if userInput starts with "." but is not .help or .ping } else { // applies if userInput does not start with a "." } }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM