簡體   English   中英

將int添加到最終數組列表

[英]Adding ints to final array list

我有一個數組列表(如下)。 列表的等效char表示形式的數字會打印出一條秘密消息(可以通過強制類型轉換來完成)。 但是在閱讀之前,我需要先向數組列表中的每個元素添加5。 但是我以為數組是最終的,我們不能更改字符串元素? (我確實嘗試使數組變為非最終值,但仍然無法將列表中的每個值加5。)您可以在下面看到我嘗試使用的代碼,但它仍會打印出列表中的原始值。 有人有指針嗎? 謝謝。

public static void main(String[] args) {
    final int[] message = { 82, 96, 103, 103, 27, 95, 106, 105, 96, 28 };
    final int key = 5;
    for (int x : message)
        x = x + key;
    for (int x : message)
        System.out.print(x + ",");
}

您沒有更改消息數組。 您只是獲得每個元素的溫度值x,然后將其增加。 即使您嘗試過,也會因為聲明為final而顯示錯誤。

增加價值,你可以做這樣的事情

int[] message =
    {82, 96, 103, 103, 27, 95, 106, 105, 96, 28};
final int key = 5;
for (int i = 0; i< message.length; i++)
    message[i]+=key; 

您不需要第二個循環:

for (int x: message) { x = x + key; System.out.print(x + ","); }

在第一個循環中,您將更改該循環的局部變量(x)。 您實際上並沒有像您期望的那樣修改數組內容。 在第二個循環中,該x變量是第二個循環的局部變量,與第一個循環的x完全不同。

嘗試這個

final int[] message = { 82, 96, 103, 103, 27, 95, 106, 105, 96, 28 };
final int key = 5;
for (int i = 0; i < message.length; i++)
  message[i] += key;
for (int i = 0; i < message.length; i++)
  System.out.print(message[i] + ",");

您的代碼無效,因為您的x是for循環中的local variable

您要在數組元素的副本中添加鍵,這不會更改數組實際元素的值。 而是這樣做。

   for (int x =0; x < message.length; x++)
        message[x] = message[x] + key;
    for (int x : message)
        System.out.print(x + ",");

更多澄清

int value = message[0];
value = value+10; // This will not change value of element at message[0];

但是我以為數組是最終的,我們不能更改字符串元素? 我確實嘗試使數組非最終

您對final和不可變之間感到困惑:

final--> 1. For primitives : you can't change the value (RHS)
         2. For non-primitives : you can't reassign the reference to another object.
         2.b. You can change the value(s) of the object to which the reference is currently pointing.

immutable - you can't change the value of the object to which the reference is pointing.

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM