Java 代码有问题。
import java.util.Random;
public class arrayTable {
public static void main (String[] args) {
System.out.println("Index\t + Value");
int Array[] = new int[10];
Random Object = new Random();
int Values;
// Assigning random values to each element of array
for(int i=0; i<Array.length;i++) {
Values= (1+Object.nextInt(50));
Array[i] = Values;
}
for(int j=0;j<Array.length;j++) {
System.out.println(j + "\t" + Array[j]);
}
}
}
在这里,我在对象旁边写了(1+),因此索引应该从1开始,但是当我运行代码时,总是从索引0开始,无论我输入2+还是3+ pr 无论如何。任何人都可以帮助指出代码的问题吗?
提前谢谢您。
最佳答案
i wrote (1+) next to the object so the index should start at 1
您在值旁边写了1+,而不是索引!
所以,你正在做的是:
array[0] = 50 + 1;
而不是:
array[0 + 1] = 50;
如果您想从索引 1 开始,您应该将其写在这里:
Array[i + 1] = Values;
但是当你在 for
内时循环,你可能会遇到 ArrayIndexOutOfBoundsException
,所以,更好的想法是:
for(int i=1; i<Array.length;i++) { //Look the "i" was initialized with 1 and not with 0.
记住:数组从 0
开始索引
如果想“跳过”第一个元素,则将上面修改为for
循环应该可以工作,但是如果你希望它从 1
运行至10
那么这是一个坏主意,因为它应该来自 0
至9
您还应该小心遵循 Java 命名约定:
-
firstWordLowerCaseVariable
-
firstWordLowerCaseMethod()
-
FirstWordUpperCaseClass
-
ALL_WORDS_UPPER_CASE_CONSTANT
并一致地使用它们,这将使您和我们更容易阅读和理解您的代码。
此外,尽量不要将类/变量命名为 Java 类名称:
Object
或Array
或List
等可能是错误的选择,还有 object
小写字母不是一个好主意,因为它也不是描述性的,正如 @nicomp 在下面的评论中所建议的
but when i type Array [i + 1] it still prints out from index 0, if for example i where to make i dice i would want it to start at index 1, is there no way to do this?
我认为您没有更改 for(int j=0;j<Array.length;j++) {
循环,从 1
开始
要制作骰子,我会:
- 创建包含 6 个槽的数组(从 0 开始)
如下所示填充它 (1 - 6)(在
for
循环内):dice[0] = 1; dice[1] = 2; ... dice[5] = 6; //Example of for loop for (int i = 0; i < dice.length; i++) { dice[i] = i + 1; }
获取一个名为
random
的随机数(0 - 5 之间)- 获取数组中位置
random
处的值
例如:
random = 3;
//dice[random] = 4;
System.out.println(dice[random]);
关于Java代码1+问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45740756/