有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java打印arraylist内容时无输出

import java.util.ArrayList;
import java.util.Iterator;
/** 
* @author Stephanie Hoyt 
* @version April 10, 2014
*/
public class Purse
{
private ArrayList<MyCoins> coins;
private int total;
/**
 * Default constructor for objects of class Purse.
 */
public Purse()
{
    coins = new ArrayList<MyCoins>();
}

/**
 * Takes Coin as a parameter and adds Coin to the Purse.
 **/
public void add(int coinValue)
{
    coins.add(new MyCoins(coinValue));
    total += coinValue;
}

/**
 * 
 */
public int getTotal()
{
    return total;
}

/**
 * 
 */
public void showCoins()
{
    coins = new ArrayList<MyCoins>();
    Iterator<MyCoins> itr = coins.iterator();
    while(itr.hasNext())
        {
            MyCoins c = itr.next();
            System.out.println(c.getName());
        }

}
}

所以我的问题是showCoins()方法。我想打印出ArrayList的内容,硬币。代码可以编译,但当我运行它时,什么也没有发生。所有其他方法都很有效。 这门课与另一门课有关,我将在下面发布

public class MyCoins
{
private String myName;
private int myValue;

/**
 * default constructor for MyCoins class.
 */
public MyCoins(String name, int value)
{
    myName = name;
    myValue = value;
}

/**
 * Non-default constructor for MyCoins class.
 */
public MyCoins(int value)
{
    myValue = value;
    if(value == 1)
        myName = new String("Penny");
    else if(value == 5)
        myName = new String("Nickel");
    else if(value == 10)
        myName = new String("Dime");
    else if(value == 25)
        myName = new String("Quarter");
    else
        throw new IllegalArgumentException("Enter the value of a US coin.");
}

/**
 * Returns the current value of coins as an integer.
 */
public int getValue()
{
    return myValue;
}

/**
 * Returns myName as a String.
 */
public String getName()
{
    return myName;
}
}

共 (2) 个答案

  1. # 1 楼答案

    showCoins()方法中删除coins = new ArrayList<MyCoins>();。它会将您钱包中当前的硬币列表替换为空列表

  2. # 2 楼答案

    您创建了一个ArrayList,但没有添加任何内容。所以得到一个迭代器,然后迭代什么都不迭代。所以没什么可打印的

    coins = new ArrayList<MyCoins>();
    Iterator<MyCoins> itr = coins.iterator();
    

    可能您试图引用coins实例字段。在这种情况下,摆脱

    coins = new ArrayList<MyCoins>();