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;
}
}
}
另外,我想在某种程度上,我可以问三个问题来创建这个程序(如某人的姓名,性别和年龄,也许更像是种族和诸如此类的东西),和然后将所有这些答案带回。就像最后说的那样,“所以,你的名字是+名字+,你是+性别+,并且你年龄+岁以上?是/否。”沿着这些线的东西。我知道有一种方法可以实现,但我不知道如何将这些响应保存在任何地方,而且我不能抓住它们,因为它们只发生在方法实例中。
对不起,花了这么长时间回到这个,但是,这有帮助!我知道了! –