简体   繁体   English

我不明白为什么我的手工回答不同

[英]I don't understand why my answer by hand is different

So here is the code:所以这里是代码:

import java.util.*;

public class HelloWorld{

     public static void main(String []args){
        ArrayList<Integer> what = new ArrayList<Integer>();
        what.add(3);
        what.add(7);
        what.add(2);
        for (int i=0; i<4;i++)
        {
            if(i%2==0)
            {
                what.add(0,i);
            }
            else
            {
                what.set(i,(what.get(i)*2));
            }
        }
        what.remove(3);
        System.out.println(what);
     }
}

When I solve this by hand, my answer comes out as: [2,0,2,2] However when plugging it in the correct answer is: [2,0,6,2] Can someone help me answer why I'm getting my answer and why the correct answer is correct?当我手动解决这个问题时,我的答案是: [2,0,2,2]但是当将它插入正确答案时是: [2,0,6,2]有人可以帮我回答我为什么得到我的答案,为什么正确答案是正确的?

Here I have debugged it using hand for you.在这里,我已经为您手动调试了它。 See where you go wrong.看看你在哪里 go 错了。 add() function adds the provided integer to the position chosen by you while the set() function replaces the provided the integer with the integer at the place chosen by you. add() function adds the provided integer to the position chosen by you while the set() function replaces the provided the integer with the integer at the place chosen by you.

在此处输入图像描述

I am not sure how you are doing it in your hand, but expected output by the program is correct.我不确定你是怎么做的,但程序预期的 output 是正确的。 You can debug it to see where you are deviating and getting [2,0,2,2].您可以对其进行调试以查看您偏离并获得 [2,0,2,2] 的位置。

At no point, the array "what" has this value.在任何时候,数组“what”都没有这个值。

i = 0, [Start: 3,7,2 ]
i = 1, [Start:  0,3,7,2]
i = 2, [Start:  0,6,7,2]
i = 3, [Start:  2,0,6,7,2]
Loop End: [2, 0, 6, 14, 2]

Remove what[3]

Final Value: [2, 0, 6, 2]
initially your list has [3,7,2] elements,
you started a loop which will run from i=0 to 3
at i=0, condition i%2==0 is true,
it will add i at first position, list become [0,3,7,2]
i=1, condition false, element at i is 3, 3*2=6, put it at i, [0,6,7,2]
i=2, condition true, put i at first position [2,0,6,7,2]
i=3, condition false, element at i is 7, 7*2= 14, put it at i, [2,0,6,14,2]
loop ends.
remove element at position 3, i.e. 14, new list [2,0,6,2]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM