IndexOutOfBoundsException当我尝试使用list.contain(...)时,不确定如何修复

时间:2017-12-01 00:41:36

标签: java-8 indexoutofboundsexception

public static void main(String[] args)  {
    List<String> stuff = new ArrayList<String>();
    List<String> fc = new ArrayList<String>();
    List<String> on = new ArrayList<String>();
    List<String> done = new ArrayList<String>();

    int d=0;
    int x=0;
    int r=0;

    //"inputs" is an array with all the inputs from the user.  
    //You will have to go through and extract the data from "inputs" and store it in     
    //a data type that works
    Scanner in = new Scanner(System.in);
    int inputs_size = 0;
    inputs_size = 100;

    String[] inputs = new String[inputs_size];
    for(int i = 0; i < inputs_size; i++) {
        String inputs_item;
        try {
            inputs_item = in.nextLine();
        } catch (Exception e) {
            inputs_item = null;
        }
        inputs[i] = inputs_item;
    }

    for(int n=0; n<inputs.length-1; n++){
        if(inputs[n]==null){
            break;
        }
        stuff.add(inputs[n]);
    }

    while(d<stuff.size()){
        if(stuff.get(d).equals("0")){
              x++;
        }
        d++;
    }

    for(int t=0; t<stuff.size(); t++){
        if(stuff.get(t).equals("0")){
            break;
        }
        fc.add(stuff.get(t));
    }

    r=fc.size();

    while(r<stuff.size()-1){
        if(stuff.get(r).equals("0")){
            r++;
            x=x-1;
        }

        if(x==4 && stuff.get(r)!="0"){
            on.add(stuff.get(r));
        }
        if(x==3 && stuff.get(r)!="0"){
            tw.add(stuff.get(r));
        }
        if(x==2 && stuff.get(r)!="0"){
            th.add(stuff.get(r));
        }
        if(x==1 && stuff.get(r)!="0"){
            fo.add(stuff.get(r));
        }
        if(x==0 && stuff.get(r)!="0"){
            fi.add(stuff.get(r));
        }
        if(x==-1 && stuff.get(r)!="0"){
            si.add(stuff.get(r));
        }
        r++;
    }

    int z=0;
    int counter = 1;
    for(; counter < fc.size(); counter++) {
        if(counter>fc.size()){
            break;
        }

        **if(fc.contains(on.get(counter)))** {
            z=0;
        }
        else{
            z=1;
            break;
        }
    }
    if(z==0){
        done.add(on.get(0));
    }
    counter=1;
    z=0;

    System.out.println(done);

    }
}

我得到一个带有星号的代码行的IndexOutOfBounds错误(fc.contains(...))。我正在尝试创建一个充当冰箱的程序,接收输入并确定我能够制作的食谱。

示例输入: (牛奶 起司 鸡蛋
蜂蜜) - 冰箱里的成分 (0) - 分隔列表 (鸡蛋和蜂蜜) - 有问题的食谱 (蛋 蜂蜜) - 食谱所需的成分,他们在冰箱里?是

所以我的输出是:鸡蛋和蜂蜜,或者我可以制作的食谱名称。

我在哪里出错?谢谢!

1 个答案:

答案 0 :(得分:0)

关注您的代码后,我认为您的on数组为空。
外观:

if(x==4 && stuff.get(r)!="0"){
  on.add(stuff.get(r));
}


这是您尝试向on添加内容的唯一时间。并且您的fcstuff尺寸将相同,因为您没有任何东西可以使它变得不同(而不是此.equals("0"),但如果您输入其他内容,则为会是一样的)。之后,我们有:

r=fc.size();

while(r<stuff.size()-1){

我们知道fcstuff具有相同的尺寸,然后r不会低于stuff.size()-1
通过不进入循环,它将保持为空。因此,任何.get()都会产生IndexOutOfBounds