2012-05-15 54 views
0

我想这样做:限制用户输入+回路

  • 限制用户输入字母只(小写和大写)不正确的输入
  • 错误信息
  • 循环,直到输入正确

不少网站有类似的问题,建议使用正则表达式,模式和匹配器。我曾看过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"); 
    } 
} 

这个编译,但我不知道这是否是正确的/最好的方式来做到这一点。但是,如果我输入不同的字符类型,它只会执行其余的代码。

如何在收到正确的字符类型时才使其执行,以及我应该如何使用户知道错误?

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

+0

你可能意思是'循环直到正确的输入',在这种情况下你的循环是哪里? – Rom1

+0

都完成了。就像我说的那样,这对我来说是新的领域。 – user10

回答

1

好的,所以这里有一些东西需要修复。我注意到的第一件事是要

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); 
+0

'bool result = true; do { String blah = sc.nextLine(); Pattern userInput = Pattern.compile(“^ [a-zA-Z] + $”); Matcher inputCheck = userInput.matcher(blah);如果(false){System.out.println(“wrong input”); } while(true); ' 这样的事情? – user10

2

这似乎是家庭作业,所以我不想放弃太多,但你想看看if statement以及whilefor循环。如果符合某些标准,这将有条件地执行代码。