![](/img/trans.png)
[英]How to make a particular string input the condition for while loop and it checks everytime an input is entered
[英]How to check entered String in a loop with condition?
我想編寫一個程序,該程序檢查給定字符限制(例如10個字符)的用戶輸入字符串。 如果輸入的字符串超過10個字符,則系統應再次提示用戶輸入有效的字符串(10個字符的單詞),直到用戶輸入有效的字符串為止。
我已經有一些代碼了,但是它還不能用,因為我不知道如何將進程重新啟動(到第1行)以重新提示用戶,或者還有其他簡單的方法嗎?
System.out.print("Input: ");
String inputChars = Input.readString();
while (inputChars.length() > 10){
System.out.print("Input: ");
String inputChars = Input.readString(); // here is mistake now
}
System.out.print("Output: ");
System.out.print("The enter has 10 chars");
我只想檢查輸入的單詞(如果超過10個字符),然后跳過它並再次提示用戶輸入不超過10個字符的單詞。 我的Java語言還不太好,所以如果這個問題很愚蠢,請向我解釋如何解決。 提前致謝
看一下你的循環:
while (inputChars.length() > 10){
System.out.print("Input: ");
String inputChars = Input.readString();
}
循環主體的第二行重新聲明了inputChars
變量。 您不能這樣做,因為它已經在范圍內。 您只想替換先前的值 :
inputChars = Input.readString();
但是,您還應該考慮重組代碼,以避免重復:
String inputChars;
do {
System.out.print("Input: ");
inputChars = input.readString();
} while (inputChars.length() > 10);
請注意,我還如何將Input
變量重命名為input
以遵循常規Java命名約定。 其實我可能會改變這兩種input
和inputChars
更描述性的-尤其是,有沒有什么樣的輸入數據意味着此刻的意思表示。
只需在開頭刪除String
:
while (inputChars.length() > 10){
System.out.print("Input: ");
inputChars = Input.readString(); // here is mistake now
}
通過以String
開頭,您正在嘗試再次重新定義相同的名稱變量。
改成:
String inputChars = ""
do {
System.out.print("Input: ");
inputChars = Input.readString();
} while (inputChars.length() > 10)
System.out.print("Output: ");
System.out.print("The enter has 10 chars");
之前,在循環之前已經聲明了inputChars
,因此您無需重新聲明變量。
do-while循環在這里是一個更好的構造,因為它可以使您的意圖更清晰,並使您的代碼更清晰。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.