0
每當我運行這個代碼,它的工作非常順利,直到while循環運行一次。它將返回並再次詢問名稱,然後跳過String b = sc.nextLine();,然後打印下一行。我得到資源泄漏
static Scanner sc = new Scanner(System.in);
static public void main(String [] argv) {
Name();
}
static public void Name() {
boolean again = false;
do
{
System.out.println("What is your name?");
String b = sc.nextLine();
System.out.println("Ah, so your name is " + b +"?\n" +
"(y//n)");
int a = getYN();
System.out.println(a + "! Good.");
again = askQuestion();
} while(again);
}
static public boolean askQuestion() {
System.out.println("Do you want to try again?");
int answer = sc.nextInt();
if (answer == 1) {
return true;
}
else {
return false;
}
}
static int getYN() {
switch (sc.nextLine().substring(0, 1).toLowerCase()) {
case "y":
return 1;
case "n":
return 0;
default:
return 2;
}
}
}
另外,我想在某種程度上,我可以問三個問題來創建這個程序(如某人的姓名,性別和年齡,也許更像是種族和諸如此類的東西),和然後將所有這些答案帶回。就像最後說的那樣,「所以,你的名字是+名字+,你是+性別+,並且你年齡+歲以上?是/否。」沿着這些線的東西。我知道有一種方法可以實現,但我不知道如何將這些響應保存在任何地方,而且我不能抓住它們,因爲它們只發生在方法實例中。
對不起,花了這麼長時間回到這個,但是,這有幫助!我知道了! –