通过索引访问Java数组位置的值 [英] Accessing the value of a Java array position by index
问题描述
我对Java真的很陌生,只是在数组上苦苦挣扎.在遵循教程的过程中,我已经写了一段代码,但是我一直在努力理解它,如果有人可以向我解释它,我将非常乐意.
I'm really new to Java and am just struggling with arrays a little bit. I've got a block of code that I've written when following a tutorial but am struggling to understand it and would love if someone could explain it to me.
我尝试使用各种不同的方法(对鸭子进行解释,将其写下来等)来解决它,但仍然无法解决.我通常不会问,而且我总是拼命地努力解决这个问题,但是这次我只是想不通.
I've tried working through it with various different methods (explaining to my duck, writing it down, etc.) and still can't get my head around it. I normally wouldn't ask and I always try desperately hard to work it out myself, but I just can't figure it out this time.
int[] values = new int[3];
values[0] = 10;
values[1] = 20;
values[3] = 30;
for(int i = 0; i < values.length; i++) {
System.out.println(values[i]);
}
我了解原因:
- for循环遍历值"中的值.
- 循环一直循环直到i小于数组中的最后一个值.
但是我不明白的是为什么我需要在 System.out.println()
语句中写入 values [i]
.是什么告诉Java在数组 values []
中可以使用 i
?
But what I don't understand is why I need to write values[i]
in the System.out.println()
statement. What tells Java that i
can be used in the array values[]
?
对不起,如果这对您来说是个琐碎的问题,但这是我想到的最佳去处.
Sorry if this is a trivial question for you but this is the best place I could think of to turn.
推荐答案
Java知道 values 是数组类型.Java中的数组由整数索引,因此这里有一个名为 i 的整数. i 从0到小于 values.length (在这种情况下为3).所以我将是0、1和2.
Java knows that values is an array type. Arrays in Java are indexed by integers, so here we have an integer called i. i goes from 0 to less than values.length (in this case is 3). So i will be 0, 1, and 2.
用0、1和2索引值等效于:
Indexing values with 0, 1, and 2 are equivalent to:
values[0]
values[1]
values[2]
这篇关于通过索引访问Java数组位置的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!