سؤال

I'm creating a bank account program to learn OOP. I made a void method called w_or_d (stands for withdrawal or deposit), but variables made inside my void are not carrying over to outside the void.

It shows my variable (finalbalance) as 0.

public class users {
  int balance;
  int finalbalance;

  public void w_or_d(int word, int amount) {

    if (word ==0) {
      int finalbalance = balance-amount;
    }
    else if (word == 1) {
      int finalbalance = balance+amount;
    } 

  }

  System.out.println(finalbalance);
}
هل كانت مفيدة؟

المحلول

You are shadowing your instance variables with duplicate method local variable definition:

    int finalbalance = balance-amount;

just do the assignment instead of re-decalaration

    finalbalance = balance-amount;

Also using keyword this will make sure that you are setting the instance variable and not the local variable in case you have two such variables with the same name. So this is much safer:

   this.finalbalance = balance-amount;

نصائح أخرى

int finalbalance = balance+amount;
int finalbalance = balance+amount;

these sentences override the

int finalbalance;

so when you

System.out.println(finalbalance);

finalbalance has no correct value.

just remove "int"

int finalbalance = balance+amount;

int finalbalance = balance+amount;

You have declared finalbalance both as a class property AND a local variable inside your (poorly named) method w_or_d().

You are altering the local one; changes to which are ignored when the local variable goes out of scope.

There are tutorials here: Lesson: Classes and Objects

or can be used after else if statement as fallow

this.finalbalance =finalbalance;

so it assign finalbalance back to the class variable.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top