String variable may not have been initialized (error diects to line 34)

前端 未结 4 554
太阳男子
太阳男子 2021-01-26 00:59

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

相关标签:
4条回答
  • 2021-01-26 01:49

    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 Strings as follows:

    "rock".equalsIgnoreCase(playerChoice);
    
    0 讨论(0)
  • 2021-01-26 01:55
    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.

    0 讨论(0)
  • 2021-01-26 01:58

    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.

    0 讨论(0)
  • 2021-01-26 01:58

    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.

    0 讨论(0)
提交回复
热议问题