我在while循环中创建了一个整数一位数的数组。 现在我想在循环之外使用保存在该数组中的值。 这甚至可能吗?
我是编程的初学者,所以我只知道基本的东西,如while,for循环和数组,我只使用main方法:public static void main(String[] args)
。
提前谢谢!
我
答案 0 :(得分:1)
为了访问您输入到数组中的元素,您必须指明元素所在的索引(位置)。例如,如果你有一个包含三个元素(10,11和12)的数组,就像这个:
int[3] array; //<-- Important that this line is outside the while loop
int i = 0;
while(i<3) { //<-- We use number three because the array has 3 elements
int[i] = 10+i;
}
为了获得数字10,你必须访问数组的第一个位置,即位置0:
int numberTen = array[0];
以下是如何打印所有数字的示例:
System.out.println(array[0]);
System.out.println(array[1]);
System.out.println(array[2]);
您也可以使用循环来执行此操作:
int j = 0;
while(j<3) {
System.out.println(array[j]);
}
危险:如果你试图访问位置3,你将得到一个IndexOutOfBounds异常,因为这个数组的最后一个位置是位置2,因为第一个位置是位置0.这就是为什么在while循环的条件下你有使用运算符&lt;而不是&lt; =。