Java 类常量最终变量
这是我的密码。我需要日期和答案保持不变。我需要一个用户输入“What is the word of the day”和“What is the response to 3*8”的答案,根据他们的答案,该答案要么被接受为正确答案,要么被拒绝,然后重试。 我一直收到这个编译器错误 错误:无法为最终变量WordOfDay赋值 错误:无法为最终变量答案赋值Java 类常量最终变量,java,variables,final,class-constants,Java,Variables,Final,Class Constants,这是我的密码。我需要日期和答案保持不变。我需要一个用户输入“What is the word of the day”和“What is the response to 3*8”的答案,根据他们的答案,该答案要么被接受为正确答案,要么被拒绝,然后重试。 我一直收到这个编译器错误 错误:无法为最终变量WordOfDay赋值 错误:无法为最终变量答案赋值 //The word of the day is Kitten import java.util.Scanner; public class S
//The word of the day is Kitten
import java.util.Scanner;
public class SchmeisserKLE41 {
public static final Scanner input = new Scanner(System.in);
public static final String wordOfTheDay = "Kitten";
public static final int answer = 24;
public static void main(String[] args) {
int attempts = 3;
System.out.printf("Please enter the word of the day:");
wordOfTheDay = input.nextLine();
do{
-- attempts;
if(attempts == 0){
System.out.printf("Sorry! You've exhausted all your attempts!");
break;
}
System.out.printf("Invalid! Try again %d attempt(s) left.", attempts);
wordOfTheDay = input.nextLine();
}
while(!wordOfTheDay.equals("Kitten"));
System.out.printf("\nWhat is the answer to 3 * 8?");
answer = input.nextInt();
System.exit(0);
}
}
wordofday=input.nextLine()
您已经设置了日期字数
。这是最终结果,所以您只能设置一次
public static final String wordOfTheDay = "Kitten";
由于WordOfDay声明为final,因此在此之后不能为其分配任何值
所有最终变量不能多次赋值
因此,请按如下所示从中删除final
public static String wordOfTheDay = "Kitten";
现在,您可以多次赋值。您需要两个不同的变量。一个用来存储当天的单词,另一个用来存储用户的猜测。所以你需要给它们取两个不同的名字。可能是
wordofday
和usersGuess
。然后,您可以在用户猜测后比较它们,方法是将循环末尾的条件更改为while(!wordofday.equals(usersGuess))代码>我如何将日期保留为“Kitten”并测试它是否正确?我如何将日期保留为“Kitten”并测试它是否正确?只需将其声明为如上所示的非最终值,并根据您的条件不断为其赋值