[英]While loop using Scanner
嗨,我正在編寫一個程序,該程序使用Scanner從用戶處獲取輸入,然后使用布爾方法檢查輸入是否最多六個字符。 問題是,如果長度小於六,我使用了while循環來不斷詢問輸入。 但是在第一個錯誤輸入之后,如果您插入六個或更多個字母的字符串,則循環仍將繼續。 請在這里是程序:
import java.util.Scanner;
public class PasswordChecker{
public static void main(String[] args) {
Scanner kbd = new Scanner(System.in);
String input;
System.out.println("Enter a password");
input = kbd.nextLine();
boolean result = LengthCheck(input);
LengthCheck(input);
while(result == false){
System.out.println("Please enter a minimum password of six characters");
input = kbd.nextLine();
}
System.out.println(input);
System.out.println(result);
}//close main
public static boolean LengthCheck(String input){
boolean result = false;
int length = 6;
if(input.length() >= length){
result = true;
}
return result;
}//LengthCheck
}//PasswordChecker
謝謝
在您的方案中,您希望在密碼長度超過六個字符時退出循環。 因此,您需要確保在while
語句中檢查該條件。
這將為您解決問題:
while(LengthCheck(input) == false){
System.out.println("Please enter a minimum password of six characters");
input = kbd.nextLine();
}
循環將繼續進行,直到您滿足LengthCheck
的要求,然后輸入了6位數字的密碼。
您需要在while循環中檢查LengthCheck()
,試試看
while(result == false){
System.out.println("Please enter a minimum password of six characters");
input = kbd.nextLine();
-> result = LengthCheck(input);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.