Search code examples
javavariablesfinalclass-constants

Class constant final variable


This is my code. I need wordOfTheDay and answer to stay the same. I need a user to input an answer for "What is the word of the day" and "What is the answer to 3*8" and depending on their answer it will either be accepted as the correct answer or rejected and they try again. I keep getting this compiler error

Error: cannot assign a value to final variable wordOfTheDay Error: cannot assign a value to final variable answer

//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);
 }
}

Solution

  • You need two different variables. One to store the word of the day, and the other to store the user's guess. So you'll need to have two different names for them. Maybe wordOfTheDay and usersGuess. Then you can compare them after the user guesses, by changing the condition at the end of your loop to while(!wordOfTheDay.equals(usersGuess));