【问题标题】:restricting user input + loop限制用户输入+循环
【发布时间】:2012-05-15 15:16:10
【问题描述】:

我想做的事:

  • 仅将用户输入限制为字母(小写和大写)
  • 错误输入的错误消息
  • 循环直到输入正确

不少有类似问题的网站建议使用正则表达式、模式和匹配器。我看过 API,这让我很困惑......

这是我尝试过的。

public class restrictinput {
    public static void main (String args [] ) {
        Scanner sc = new Scanner (in);
        System.out.println ("Enter  blah ");
        String blah = sc.nextLine();
        Pattern userInput = Pattern.compile("^[a-zA-Z]+$");
        Matcher inputCheck = userInput.matcher("blah");
    }
}

这可以编译,但我不确定这是否是正确/最佳的方法。但是,如果我输入不同的字符类型,它只会执行其余的代码。

如何仅在收到正确的字符类型时才执行它,我应该使用什么来让用户知道错误?

如果给出的代码有误,我应该怎么改?

【问题讨论】:

  • 您的意思可能是“循环直到输入正确”,在这种情况下,您的循环在哪里?
  • 两者都完成了。就像我说的,这对我来说是新的领域。

标签: java java.util.scanner


【解决方案1】:

这似乎是家庭作业,所以我不想透露太多,但您想查看if statement 以及whilefor 循环。如果满足某些条件,这将有条件地执行代码。

【讨论】:

    【解决方案2】:

    好的,这里有几件事需要解决。我注意到的第一件事是你想要

    userInput.matcher(blah);
    

    不是

    userInput.matcher("blah");
    

    因为你匹配的是字符串,而不仅仅是"blah"

    现在回答您的大部分问题。您需要做的第一件事是查看Matcher 对象。具体查看 Matcher.find()。

    第二件事是您需要在代码中添加某种条件循环,以便它不断要求输入。可能是这样的:

    bool result = true;
    do {
        String blah = sc.nextLine();
        Pattern userInput = Pattern.compile("^[a-zA-Z]+$");
        Matcher inputCheck = userInput.matcher("blah");
        result = //boolean check from your matcher object
        if(result) {
            //Complain about wrong input
        }
    } while(result);
    

    【讨论】:

    • bool result = true; do{ String blah = sc.nextLine(); Pattern userInput = Pattern.compile("^[a-zA-Z]+$"); Matcher inputCheck = userInput.matcher(blah); if(false) { System.out.println("wrong input"); } while (true); 是这样的吗?
    猜你喜欢
    • 1970-01-01
    • 2013-07-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多