vicbab
vicbab

Reputation: 31

How can I use a variable set on a different method?

In my code, the variable "targetNumber" can't be accessed on a different method. How do I make it possible? In the method "jButton3Action...", I set the variable. And in the method "jButton1Action..." I try to call it, but it's returning an error:

Cannot find symbol Symbol: variable targetNumber location: class ggui

public static int randInt(int min, int max){
    Random rand = new Random();

    int targetNumber = rand.nextInt((max - min) + 1) + min;

    return targetNumber;
}
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {                                         
    // TODO add your handling code here:
    final int targetNumber = randInt(1, 10000);
}
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
    // TODO add your handling code here:

    String tooHigh = "Too High!";
    String tooLow = "Too Low!";
    String gotIt = "Got it!";
    int guess;
    guess = Integer.parseInt(jTextField1.getText());

    if (!(guess == targetNumber)){
        guess = Integer.parseInt(jTextField1.getText());
        if(guess > targetNumber){
            resultField.setText(String.valueOf(tooHigh));
        }
        else if(guess < targetNumber){
            resultField.setText(String.valueOf(tooLow));
        }

    }
    else{
        resultField.setText(String.valueOf(gotIt));
    }

Upvotes: 0

Views: 69

Answers (1)

Arnav Borborah
Arnav Borborah

Reputation: 11787

Instead of having to mess around with scope, instead make the variable a private field of the class, so all methods can access it. This is convenient for all methods, and will remove unnecessary code. Use it like this:

private int targetNumber;

In private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) { do this:

targetNumber = randInt(1, 10000);

In the rest of your program, the code should perform as expected. Also, don't call the variable in randint(): targetNumber, because the compiler may get confused as to which one you are referring to in the return statement.

Upvotes: 3

Related Questions