這個問題在這里已經有了答案: 掃描儀在使用 next() 或 nextFoo() 后跳過 nextLine() 嗎? (22 個回答) 2 小時前關閉。
我正在為學校做一個專案,我正在努力讓你可以在解決計算機提出的一系列問題的同時為自己設定一個名字。我希望用戶能夠在分配名稱后立即更改他們的姓名,如果他們不喜歡他們放下的內容或輸入錯誤的內容。現在,程式第一次正確分配用戶想要的名稱,但是當它回傳回圈以將其更改為其他內容時,該字串留空。 控制臺輸出 '''
import java.util.*;
public class JavaInputProdject
{
public static void main(String args[])
{
int i=0;
boolean boo = false;
int likeab = 0;
byte age;
boolean Old=false;
boolean aAge=true;
String user="User";
String un = user "> ";
Scanner bob = new Scanner(System.in);
System.out.print("Bob> Hey User, My name is BOB.... what is your name?\n" un);
do
{
user = bob.nextLine();
System.out.println("Bob> This is the Username you want? \"" user "\"(true/false)");
System.out.print(un);
if(bob.nextBoolean()==true)
{
boo = true;
un = user "> ";
}
else
{
if(i>=3)
{
System.out.println("Bob> I realize it is kind of hard to pick a name but could you hurry up?");
}
System.out.print("Bob> Please type in a new Username\n" un);
bob.next();
i ;
}
} while(boo==false);
}
}
'''
uj5u.com熱心網友回復:
您需要更換線路bob.next()(靠近年底do-while與回圈)bob.nextLine()。
我相信這bob.next()不會消耗由于在bob.nextBoolean()呼叫后按 <ENTER> 鍵而輸入的換行符。因此,該user = bob.nextLine();行(在do-while回圈開始處)在第二次和后續回圈迭代中使用該換行符。所以替換bob.next()withbob.nextLine()將解決問題。
為了完整起見,這里是更正后的代碼:
import java.util.Scanner;
public class JavaInputProdject {
public static void main(String[] args) {
int i = 0;
boolean boo = false;
int likeab = 0;
byte age;
boolean Old = false;
boolean aAge = true;
String user = "User";
String un = user "> ";
Scanner bob = new Scanner(System.in);
System.out.print("Bob> Hey User, My name is BOB.... what is your name?\n" un);
do {
user = bob.nextLine();
System.out.println("Bob> This is the Username you want? \"" user "\"(true/false)");
System.out.print(un);
if (bob.nextBoolean()) {
boo = true;
un = user "> ";
}
else {
if (i >= 3) {
System.out.println(
"Bob> I realize it is kind of hard to pick a name but could you hurry up?");
}
System.out.print("Bob> Please type in a new Username\n" un);
bob.nextLine();
i ;
}
} while (boo == false);
}
}
參考Scanner is skipping nextLine() after using next() or nextFoo()?
uj5u.com熱心網友回復:
當您想根據錯誤標志獲得正確的用戶名時,您不會向用戶初始化值。你應該這樣寫bob.nextLine:
System.out.print("Bob> Please type in a new Username\n" un);
user = bob.nextLine();
i ;
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/321779.html
標籤:爪哇 细绳 java.util.scanner 用户输入
上一篇:在給定字串中搜索一組子字串
