2014-02-28 45 views
0

我有一个数组列表(如下)。列表的等价字符表示的数字打印出一个秘密消息(可以通过类型转换完成)​​。但在我读之前,我需要首先将5添加到数组列表中的每个元素。但我认为数组是最终的,我们不能改变字符串元素? (我尝试过让数组非终极,但仍然无法将列表中的每个值递增5)。您可以看到我尝试在下面使用的代码,但它仍然会列出列表中的原始值。有没有人有任何指针?谢谢。将int添加到最终数组列表中

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 + ","); 
} 

回答

3

你不改变消息数组。你只是得到每个元素的临时值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; 
0

你不需要那么第二个循环:

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

在第一循环中,你是改变一个变量(x)在该循环中是本地的。你实际上并没有像你期望的那样修改阵列内容。在第二个循环中,x变量对第二个循环是局部的,并且与第一个循环的x完全不同。

0

试试这个

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是一个local variable for循环。

0

您正在数组元素的副本中添加键,这不会更改数组的实际元素的值。而是这样做。

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]; 
0

但我认为作为数组是最终的,我们不能改变 字符串元素?我也尝试使阵列非最终

你感到困惑最终的和不可改变之间:

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.