目前正在进行分配,但我是编程新手,所以想知道如何向已经具有现有类的不同类中的变量添加值
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
}
实际代码
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);
我们在这里做什么,
我们正在创建一个 OtherClass
类的对象,对象名称为temp
。
然后我们在属性 a
中分配值 5对象 temp
然后我们添加原始变量 b
的值进入变量 temp.a
.
上式的总和被赋值为 temp.a
的值
然后我通过 System.out.println(temp.a);
打印最后的总和
关于Java赋值,为不同类中的变量添加值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54652334/