gpt4 book ai didi

java - Java中的钱包转账方法

转载 作者:行者123 更新时间:2023-12-01 06:08:10 26 4
gpt4 key购买 nike

我正在参加 Java 初级类(class),并且正在电子钱包实验室工作。

我需要将一个钱包(捐赠者钱包)的钱包内容转移到另一个钱包(接收者钱包)的末尾。

我相信我的构造函数设置正确。

    import.java.util.Arrays;

public class Wallet
{
private static final int MAX = 10; //Max possible # of banknotes in a wallet

// instance variables
private int contents[]; //array of banknotes
private int count; //number of banknotes stored in contents[]

/**
* Default constructor for objects of class Wallet
*/
public Wallet()
{
// initialize instance variables
contents = new int[MAX];
count = 0;
}

/**
* Overloaded constructor for objects of class Wallet
*/
public Wallet(int a[])
{
contents = new int[MAX];

for (int i = 0; i<a.length; i++)
{
contents=a;
if (contents[i] > 0)
count++;
}
}

但需要帮助验证我编写的以下 add() 方法是否正确:

public void add(int banknote)//Not sure if this is right
{
StringBuilder sb = new StringBuilder();

for (int i = 0; i<contents.length; i++)
sb.append(contents[i] + ", ");

sb.append(banknote);

count++;

}

或者应该是:

 contents[count] = banknote;
count++;

我还需要将捐赠者钱包的内容转移到接收者钱包,清空捐赠者钱包并添加到接收者,我编写了以下代码,但它似乎关闭并且无法正常工作:

 public void transfer(Wallet donor)
{

for(int i = 0; i < count; i++)
{
add(donor.contents[i]);
count++;
}
donor.count=0;
}

关于我可能在哪里出错的任何指导,已经花了几个小时了..谢谢

最佳答案

嗯,这应该可以解决一些问题:

public Wallet(int a[]) {
contents = new int[MAX];
count = 0;
for (int i = 0; i < a.length; i++) {
if (a[i] > 0)
contents[count++] = a[i];
// only increase your content position for actual notes
}

public void add(int banknote) {
contents[count++] = banknote;
/* this version makes a lot more sense
* as you actually mutate your instance */
}

public void transfer(Wallet donor) {
for(int i = 0; i < donor.count; i++) // gotta use donor.count here
add(donor.contents[i]);
donor.count=0;
}

关于java - Java中的钱包转账方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40580664/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com