2012-05-15 55 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循環。如果符合某些標準,這將有條件地執行代碼。