I\'ve been trying to get the string initialize, but to no avail. I have tried all of the solutions I have come across and I am not sure whether it is because of my ineptness or
You can initialize the values of Strings
in two ways:
String abc = "I love basketball";
or
String abc = new String("I love basketball");
What you are seeing is a warning and not an error. If you insist on not putting a value into the String
, just do
String abc = null;
or
String abc = ""
In the latter case, your String is initialized to the characters between the quotations. Nothing, basically, but it is not null
.
To avoid potential NPE
problems, compare the String
s as follows:
"rock".equalsIgnoreCase(playerChoice);
String computer; // not initialized
change this to
String computer = null; or ""// initialized
if (player.compareTo(computer) == 0)
because, the variable computer will assigned based on the condition. If the above condition you mentioned is not satisfied. The value is none, so only it show the error.
The compilator see you have String computer. He can also see that this computer is initialized for answer 1 or 2 or 3. But because it cant read logic, it does not know anything about if answer can be or cannot be lower or higher so it is assuming the worst possibility - that computer will not be initialized.
Just change your up line to
String computer = "";
and it should be fine.
If I understand your question at all, than keep in mind you can't do this in Java:
String str = "here is some
random text";
What you can do is
String str = "here is some " +
"random text";
In other words - can't break a string at the end of the line, gotta close it and use a +
sign.