【问题标题】:data.put() throws IndexOutOfBoundsExceptiondata.put() 抛出 IndexOutOfBoundsException
【发布时间】:2014-10-14 08:04:25
【问题描述】:

所以我有这个代码来输入指定数量商品的订单和价格 公共类 SetMenu0 {

private double price;
private int size;
private String output;
private String priceOutput;

ArrayList orderList = new ArrayList<String>();
ArrayList priceList = new ArrayList<Double>();

public SetMenu0()
{
    Scanner input = new Scanner(System.in);
    System.out.print("Enter New Order?(Y)(N): ");
    String init = input.nextLine();

    if(init.equalsIgnoreCase("y"))
    {
        System.out.print("Enter Number of Orders: ");
        size = input.nextInt();

        for(int i = 0; i<=size; i++)
        {
            i++;
            System.out.print("Enter Order: ");
            orderList.add(input.next());
            System.out.print("Enter Price: ");
            priceList.add(input.nextDouble());
        }
    }
}

public ArrayList getOrd()
{
    return orderList;
}

public ArrayList getPri()
{
    return priceList;
}

public int getSize()
{
    return size;
}

}

现在,当我将它与 TreeMap 一起使用时,我在这里得到一个 indexOutOfBoundsException 公共静态无效主要(字符串 [] 参数) { //空白工作簿 XSSFWorkbook 工作簿 = new XSSFWorkbook();

    //create blank sheet
    XSSFSheet sheet = workbook.createSheet("Food");

    SetMenu0 set = new SetMenu0();

    ArrayList orderList = set.getOrd();
    ArrayList priceList = set.getPri();

    int size = orderList.size();
    Map<String, Object[]> data = new TreeMap<String, Object[]>();
    data.put("1", new Object[]{"Order", "Price"});
    try{
    for(int i=0; i<size; i++)
    {
        int in = i+2;
        String lineNum = ""+in;
        data.put(lineNum, new Object[]{orderList.get(i), priceList.get(i)});
    }
    }
    catch(IndexOutOfBoundsException e)
    {
        System.out.print("problem");
    }

将大小设置为 3 以上时会发生异常。

【问题讨论】:

    标签: for-loop map indexoutofboundsexception treemap


    【解决方案1】:

    您的问题可能出在这一点:

    for(int i = 0; i<=size; i++)
        {
            i++;
            System.out.print("Enter Order: ");
            orderList.add(input.next());
            System.out.print("Enter Price: ");
            priceList.add(input.nextDouble());
        }
    

    尝试从循环体中删除 i++。

    【讨论】:

    • 哈哈哈。非常感谢。这困扰了我一段时间,太傻了
    猜你喜欢
    • 2023-03-28
    • 2013-05-20
    • 1970-01-01
    • 1970-01-01
    • 2020-05-11
    • 2021-12-20
    • 2018-07-31
    • 2016-06-05
    • 1970-01-01
    相关资源
    最近更新 更多