如果用戶輸入了某些內容并且它在我的代碼中使陳述句為假,我想回圈我的掃描儀,如果用戶輸入了錯誤的陳述句,回圈將繼續,但如果我輸入正確的陳述句,它仍然會繼續。
Scanner sc = new Scanner(System.in);
System.out.println("Enter your student number: ");
String sn = sc.nextLine();
String REGEX = "[0-9]{4}.[0-9]{2}.[0-9]{3}";
Pattern pattern = Pattern.compile(REGEX);
Matcher matcher = pattern.matcher(sn);
do {
if (matcher.matches()) {
System.out.println("You have succesfully logged in");
System.out.println("Hello " sn " welcome to your dashboard");
}
else
System.out.println("Please enter your student number in this format: 'xxxx-xx-xxx' ");
System.out.println("Enter your student number: ");
sc.nextLine();
} while (true);
uj5u.com熱心網友回復:
Matcher matcher = pattern.matcher(sn);
這將模式與當前在“sn”中的內容相匹配。如果 'sn' 發生變化,則不會影響匹配器。如果您在沒有將結果分配給任何內容的情況下讀取另一行,則不會影響 'sn' 或匹配器。
而且你沒有回圈終止——它只是“在真時做”,沒有出路。
所以,三個問題:
匹配器需要在回圈內創建。
第二次 nextLine 呼叫的結果需要分配給 'sn'
你需要一個回圈終止。我建議一個標志,'loggedIn',最初為 false,在成功匹配時設定為 true,回圈以 'while (!loggedIn)' 結束
uj5u.com熱心網友回復:
我會這樣重寫
Scanner sc = new Scanner(System.in);
System.out.println("Enter your student number: ");
String sn = sc.nextLine();
String REGEX = "[0-9]{4}.[0-9]{2}.[0-9]{3}";
Pattern pattern = Pattern.compile(REGEX);
while(!pattern.matcher(sn).matches()) {
System.out.println("Please enter your student number in this format: 'xxxx-xx-xxx' ");
System.out.println("Enter your student number: ");
sn = sc.nextLine();
}
System.out.println("You have succesfully logged in");
System.out.println("Hello " sn " welcome to your dashboard");
uj5u.com熱心網友回復:
在 do while 回圈中獲取輸入掃描和模式匹配器
String sn;
Matcher matcher
do {
sn = sc.nextLine();
matcher= pattern.matcher(sn);
if (!matcher.matches()) {
System.out.println("Please enter your student number in this format: 'xxxx-xx-xxx' ");
System.out.println("Enter your student number: ");
}
} while (true);
System.out.println("You have succesfully logged in");
System.out.println("Hello " sn " welcome to your dashboard");
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/477838.html
標籤:爪哇 正则表达式 循环 java.util.scanner
上一篇:查找有條件的兩個日期之間的天數
