0

currently doing an assignemnt but i'm new to programming so was wondering how you add a value to a variable in a different class which already has an existing class

    class OtherClass {
        int a;
    }
    public class Main Class{
      public static void main(String[] args) {
        int b = 7;
        OtherClass temp = new OtherClass();
        OtherClass.a = 5
        OtherClass.put(b) //this is where I'm not sure how to add b to a
}

Actual Code

public static void main(String[] args) { 
// TODO Auto-generated method stub 
System.out.print("Enter amount of money you have: "); 
Scanner input = new Scanner(System.in); 
Wallet bettersWallet = new Wallet(); 
bettersWallet.moneyAvailable = input.nextDouble(); //then had a function which played out a bet and added/took away winnings from the bet 

 int winnings = 5;
 bettersWallet.moneyAvailable +=winnings; //Will setMoneyAvailable function work in this scenario aswell?

}

class Wallet {
    double moneyAvailable;
    double openingCash;
    public void setMoneyAvailable()
    {
        moneyAvailable += ChuckALuckDiceGame.winnings;
    }
1
  • error in your code, won't compile according to me. winnings is not declared. Commented Feb 12, 2019 at 14:50

1 Answer 1

1
int b = 7;
OtherClass temp = new OtherClass();
temp.a = 5;
temp.a += b; //Same as temp.a = temp.a + b;
System.out.println(temp.a);

What we are doing here, We are creating an object of class OtherClass, the name of the object is temp. Then we are assigning the value 5 in the attribute a of object temp

Then we are adding the value of primitive variable b into the variable temp.a.

The sum of the above equation is being assigned to the value of temp.a

Then I am printing the sum at the end through System.out.println(temp.a);

Sign up to request clarification or add additional context in comments.

4 Comments

That's what I had but for some reason the value wouldn't change
@MonoConman you might be doing temp.a + b. See I have written temp.a += b;
@MonoConman Basically when we add two variables, we also have to save it somewhere. so you could assign them like this temp.a = temp.a + b;
@MonoConman you have it a little bit wrong. you need to read about functions, by value, by reference, function parameters, etc. In your answer, i see chuckALuckGame.winnings but winnings is not a static variable. it is declared inside the main function, so it won't reach the setFunction at all, unless you send it as a parameter.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.