简体   繁体   English

Java赋值,将值添加到不同类中的变量

[英]Java Assignment, add value to variable in different class

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;
    }
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 . 我们在这里做的是,我们正在创建类OtherClass的对象,该对象的名称为temp Then we are assigning the value 5 in the attribute a of object temp 然后我们在对象temp的属性a中分配值5

Then we are adding the value of primitive variable b into the variable temp.a . 然后,我们将原始变量b的值添加到变量temp.a

The sum of the above equation is being assigned to the value of temp.a 上式的总和被赋予temp.a的值

Then I am printing the sum at the end through System.out.println(temp.a); 然后我通过System.out.println(temp.a);在最后打印总和System.out.println(temp.a);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM