簡體   English   中英

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

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

所以這里是代碼:

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);
     }
}

當我手動解決這個問題時,我的答案是: [2,0,2,2]但是當將它插入正確答案時是: [2,0,6,2]有人可以幫我回答我為什么得到我的答案,為什么正確答案是正確的?

在這里,我已經為您手動調試了它。 看看你在哪里 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.

在此處輸入圖像描述

我不確定你是怎么做的,但程序預期的 output 是正確的。 您可以對其進行調試以查看您偏離並獲得 [2,0,2,2] 的位置。

在任何時候,數組“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