我在java遇到了用户输入的麻烦,希望有人能帮忙:)用户声明2d数组将有多大(数字d是正方形数组的边),然后输入一个数字“n”,它告诉程序将有多少个数字的输入,然后需要输入这些数字(例如,如果n=4,输入必须是sth like: 5 17 3 20。我已经为单行数组写了同样的事情
for(i=0;i<=n;i++) {
arr[i]=sc.nextInt();
}
但是我在为二维数组做基本相同的事情时遇到了麻烦。有什么想法吗?
使用两个嵌套循环和索引,如arr[i][j]
int d=sc.nextInt(); //length of rows and columns
int n=sc.nextInt(); //user input how many numbers
int[][] array=new int[d][d]; //length and heigth of array
for (int i=0;i<d;i++) {
for(int j=0;j<d;j++) {
array[i][j]=sc.nextInt();
}
}
int distance=0;
int c=0;
for(int i=0;i<d;i++){
for(int j=0;j<d;j++){
array[i][j]=c;
c++;
}
}
最后是别的,我只是想让整件事被看到,如果我在其他地方错过了什么。
抱歉,我还没有评论的能力,所以我将此作为答案发布。本质上,您需要使用如上所述的嵌套for循环。我会为您提供一个基本模板
for (int i = 0; i < length; i ++){
for (int j = 0; j < width; j ++){
if (counter < userInput){
counter++;
arr[i][j] = value;
} else {
break;
}
}
}