我在完善一种传输方法来传输2个数组列表中的内容时遇到麻烦。我需要使用For-Each循环来执行此操作,但是目前该方法仅传输数组列表中的第一项,仅此而已。
package assignment;
import java.util.ArrayList;
/**
* A purse holds a collection of coins
*
* @author type your name
*/
public class Purse {
ArrayList<String> coins;
ArrayList<String> rcoins;
/**
* Constructs an empty purse.
*/
public Purse() {
coins = new ArrayList<String>();
rcoins = new ArrayList<String>();
}
/**
* Add a coin to the purse
*
* @param coinName the coin to add
*/
public void addCoin(String coinName) {
coins.add(coinName);
}
/**
* Return a string describing the object
*
* @return a string in the format "Purse[coinName1, coinName2, ...]"
*/
public String toString() {
if (coins.size() == 0)
return "Purse[]";
String output = "Purse[";
for (String coin : coins)
output = output + coin + ", ";
// remove the last ", "
output = output.substring(0, output.length() - 2);
return output + "]";
}
public String reverse() {
if (coins.size() == 0)
return "Purse[]";
String output = "Reverse Purse[";
for (String coin : coins)
rcoins.add(0, coin);
for (String coin : rcoins)
output += coin + ",";
output = output.substring(0, output.length() - 1);
return output + "]";
}
public void transfer(Purse a, Purse b) {
for (String coin : a.coins) {
b.coins.add(coin);
coins.remove(coin);
}
}
public String sameContents(Purse a, Purse b) {
String eq = "";
int size;
if (a.coins.size() > b.coins.size())
size = b.coins.size();
else
size = a.coins.size();
for (int i = 0; i < size; i++) {
if (a.coins.get(i).equals(b.coins.get(i)))
eq = "They are equal";
else
eq = "They are not equal";
}
return eq;
}
}
我的测试员
package assignment;
public class PurseTester {
public static void main(String[] args) {
//Create new Purses
Purse p = new Purse();
Purse q = new Purse();
//Add coins
p.addCoin("Nickel");
p.addCoin("Quarter");
p.addCoin("Dime");
q.addCoin("Penny");
q.addCoin("Quarter");
//Print contents of Purse P and the reversed contents
System.out.println(p.toString());
System.out.println("\n" + p.reverse());
//Print contents of Purse Q
System.out.println("\nOther " + q.toString() + "\n");
//Call the transfer method to transfer the contents of Purse Q into Purse P
q.transfer(q, p);
//Print contents after transfer
System.out.println(p.toString());
System.out.println("Other " + q.toString());
System.out.println("\n");
//Compare purses P and Q to see if they share contents, print reslt
System.out.println(p.sameContents(p, q));
}
}
最佳答案
public void transfer(Purse a, Purse b)
{
for(String coin : a.coins){
b.coins.add(coin);
coins.remove(coin);
}
您的错误是在这条线上:
coins.remove(coin);
那就是从属于
this
对象的钱包中删除硬币,这与您在测试代码中将它们转移到的钱包相同。您添加硬币,然后立即将其从相同的钱包中取出。您应该将它们从钱包a
中删除。因为要在
transfer
对象上调用Purse
,所以最好只包含一个参数。调用该方法的Purse
应该是要从中取出或转移到的钱包,参数应该是另一个钱包。