Home > Software design >  Why is Java forcing me to initialize my String before letting the user input the value of the String
Why is Java forcing me to initialize my String before letting the user input the value of the String

Time:08-22

I'm essentially making a small, simply "twenty questions" style program, using nested if-statements to try to guess what object the user is thinking based on clarifying questions. I'm using the if statements to eventually give the user a "result" at the end, using a String variable called "result".

My ultimate confusion lies in which the compiler is stating that "variable response may have not been initialized". To which, based on the code, I would think it is after the if statements.

import java.util.Scanner;

public class TwoQuestions {
  public static void main (String args[] ) {

    Scanner kb = new Scanner(System.in);

    String answer1, answer2, response;

    System.out.println("\n[Two Questions]\nThink of an object, and I'll try to guess it.");
    System.out.println("Is it an \"animal\", a \"vegetable\", or a \"mineral\"? (Type an answer exactly as quoted)");
    answer1 = kb.nextLine();
    System.out.println("Is it bigger than a breadbox? (yes/no)");
    answer2 = kb.nextLine();

    // example "response" based on user decisions
    if (answer1 == "animal" || answer1 == "Animal") {
      response = "yes";
      if (answer2 == "yes" || answer2 == "Yes") {
        response = "squirrel";
      }
    }
    // more if statements...

    // final machine "response" to user"
    // TODO: Figure out why *this* "response" requires initialization before if statements.
    System.out.println("My guess is that you are thinking of a "   response   ".\nI would ask you if I'm right, but I don't actually care.");

  }
}

CodePudding user response:

  1. Like mad programmer said use String equals function to compare string.
  2. Yes it will need to be initialize before compilation can take place. If Im not wrong you can initialize with Null, or " ", empty string.
  • Related