gpt4 book ai didi

Java 重复局部变量。难住了

转载 作者:行者123 更新时间:2023-12-02 01:36:57 26 4
gpt4 key购买 nike

我是编码新手,正在尝试让我的第二个程序运行。它的作用非常简单,但它在第 24 行“重复局部变量确认”上抛出错误。不太明白为什么它不喜欢我正在做的事情。

Scanner userInput = new Scanner(System.in);  
char confirm;

do{

System.out.println("Welcome to the story teller");
System.out.println("What is your name?");
String name = userInput.nextLine();

System.out.println("How old are you?");
int age = userInput.nextInt();

System.out.println("What country would you like to visit?");
String country = userInput.nextLine();

System.out.println("Great! So your name is" + name + ", you are" + age + "years old and you would like to visit" + country + "?");
System.out.println("Press Y to continue or N to start over");
char confirm = userInput.next().charAt(0);

if (confirm !='y' || confirm !='n'){
System.out.println("Sorry that input is not valid, please try again");
}
else {
System.out.println(name + "landed in" + country + "at the age of" + age + ".");
}
} while(confirm == 'Y'|| confirm == 'y');

最佳答案

您声明了两次confirm。将第二个声明更改为仅分配给它,您应该没问题:

confirm = userInput.next().charAt(0);
// No datatype, so you aren't declaring confirm, just assigning to it

关于Java 重复局部变量。难住了,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55097138/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com