javaandroidstringrandomandroid-toast

String isn't initialized in Toast (android)


package com.example.higherorlower;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import java.util.*;

public class MainActivity extends AppCompatActivity {

    public void ClickFunc(View varView)
    {
        EditText num=(EditText) findViewById(R.id.numID);
        int intNum=Integer.parseInt(num.getText().toString());
        int max=20;
        int min=1;
        int random = new Random().nextInt((max - min) + 1) + min;

        String str;
        if(random==intNum)
        {
            str="Correct! Try again!";
        }
        else if(random>intNum)
        {
            str="Lower!";
        }
        else if(random<intNum)
        {
            str="Higher!";
        }

        Toast.makeText(MainActivity.this,str,Toast.LENGTH_LONG).show();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
}

Problem: Variable 'str' might not have been initialized

I want to try generate random number and play 'guess number' game.But in Toast, it says, str is not initialized! How can I solve this problem?


Solution

  • Look to your use-case and think "if I cant show "Correct! Try again!" or "Lower!" or "Higher!", what should I display then?.

    if(random==intNum)
        {
            str="Correct! Try again!";
        }
        else if(random>intNum)
        {
            str="Lower!";
        }
        else if(random<intNum)
        {
            str="Higher!";
        } else {
             // maybe I can add a default display here?
        }
    

    Otherwise, just initialize your str to an empty string "" or null

    String str = "";
    

    or

    String str  = null;
    

    However, setting it to null is a guaranteed NullPointerException if none of those condition blocks is executed, and NullPointerException will crash your app.

    Specifically, when Toast receives a null value in its text parameter, the system will give you this error log:

    Caused by: java.lang.IllegalStateException: You must either set a text or a view