Matthias Müller
Matthias Müller

Reputation: 59

Android Studio - JAVA - Variable might not have been initialized

I'm completely new to JAVA / Android so I take a course on udemy to learn that. This is the code where I stuck:

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;

import java.util.Random;



public class MainActivity extends AppCompatActivity {

    public void guessclick(View view){
        int randomNumber;
    }

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

        Random rand = new Random();
        randomNumber = rand.nextInt(20) + 1;
    }
}

This is exactly the same code which the teacher in the lesson video got and it works by him but I get error: Variable randomNumber might not have been initialized and when I put randomNumber in the "Toaster" and run the app is crash. Do someone know the solution? I found answers with same issue but with another codes and it didn't help me.

Upvotes: 0

Views: 4785

Answers (3)

aya hareedy
aya hareedy

Reputation: 1

Because randomNumber is a local variable ,you can't use local variables outside it scope

Upvotes: 0

Daniel
Daniel

Reputation: 57

You can try: Because you use "randomNumber" like global value

public class MainActivity extends AppCompatActivity {


    int randomNumber;


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

        Random rand = new Random();
        randomNumber = rand.nextInt(20) + 1;
    }
}

Upvotes: 2

Jeffrey Blattman
Jeffrey Blattman

Reputation: 22637

That code is wrong and won't compile. int randomNumber; declares a local variable that goes out of scope immediately after the guessclick() method returns. It's subsuquent use in onCreate() will not compile as that variable has not been declared in scope to that method.

I'm guessing they meant to declare randomNumber as an instance field of MainActivity,

public class MainActivity extends AppCompatActivity {
        int randomNumber;

Upvotes: 4

Related Questions