Java 限制用户输入+;环

Java 限制用户输入+;环,java,java.util.scanner,Java,Java.util.scanner,我想做的是: 仅将用户输入限制为字母(小写和大写) 输入错误时出现错误消息 循环直到输入正确 有很多类似问题的网站建议使用正则表达式、模式和匹配器。我看过API,它让我很困惑 这是我试过的 public class restrictinput { public static void main (String args [] ) { Scanner sc = new Scanner (in); System.out.println ("Enter b

我想做的是:

  • 仅将用户输入限制为字母(小写和大写)
  • 输入错误时出现错误消息
  • 循环直到输入正确
有很多类似问题的网站建议使用正则表达式、模式和匹配器。我看过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");
    }
}
这是可以编译的,但我不确定这是否是正确/最好的方法。但是,如果我输入不同的字符类型,它只执行代码的其余部分

如何仅在接收到正确的字符类型时使其执行,以及应该使用什么来让用户知道错误


如果给出的代码是错误的,我应该怎么做才能改变它呢?

这看起来像是家庭作业,所以我不想透露太多,但您需要了解or循环以及or循环。如果满足某些条件,这将有条件地执行代码。

这看起来像是家庭作业,所以我不想透露太多,但您希望了解or循环以及or循环。如果满足某些条件,这将有条件地执行代码。

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

userInput.matcher(blah);
不是

因为您正在匹配字符串,而不仅仅是
“blah”

现在回答你的大部分问题。你需要做的第一件事就是看这个物体。具体查看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);

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

userInput.matcher(blah);
不是

因为您正在匹配字符串,而不仅仅是
“blah”

现在回答你的大部分问题。你需要做的第一件事就是看这个物体。具体查看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(“错误输入”);}while(true);
类似这样的东西?
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(“错误输入”);}while(true);
类似的内容?