[英]Writing a for loop for a 2d Array?
我有一个程序,用户正在给程序指定数组的大小,即(列和行的大小),我试图给数组中的每个位置赋予相同的值。 我的循环有问题,就在这里。
for(int i = 0; i < row; i++){
for(int j = 0; j < col; j++){
//CODE
}
}
我可以看到问题是我正在尝试为一个不存在的职位提供价值,但是我不知道如何解决此问题。 任何帮助,将不胜感激 :)
尝试使用length
,而不是用户输入 :
// ask user for sizes
int col = ...;
int row = ...;
// declare the array, let it be of type int
// it's the last occurence of "row" and "col"
int[][] data = new int[row][col];
// loop the array
for (int r = 0; r < data.length; ++r) { // <- not "row"!
int[] line = data[r];
for (int c = 0; c < line.length; ++c) { // <- not "col"!
// do what you want with line[c], e.g.
// line[c] = 7; // <- sets all array's items to 7
}
}
使用实际数组的尺寸只会阻止您访问不存在的项目
根据您提供的代码片段,您似乎还不错。 也许数组未正确初始化,或者您不匹配行号和列号。 尝试使用比“ i”和“ j”更具体的变量名。
在java中
try{
for(int i = 0; i < row; i++){
for(int j = 0; j < col; j++){
//CODE
}
}
}catch(IndexOutOfBoundsException exp){
System.out.printlv(exp.getMessage());
}
首先,是什么让您说“您可以看到问题是我试图为一个不存在的职位提供价值”? 您看到什么症状使您相信这一点?
从表面上看,您的代码看起来不错,但是(这是一个很大的数目)您省略了最重要的代码位,即2D数组的声明,以及在循环体内分配值的部分到数组成员。 如果添加这些内容,则我或其他人可能会进一步提供帮助。
解:
int matriz[][] = new int [row][col];
for(int i = 0; i <row; i++){
for(int j = 0; j < col; j++){
matriz[i][j] = 0;
}
}
//try this one
import java.util.Scanner; //Scanner class required for user input.
class xyz
{
public static void main(String ar[])
{
int row,col;
Scanner in=new Scanner(System.in); //defining Object for scanner class
System.out.println("Enter row");
row=in.nextInt();
System.out.println("Enter Column");
col=in.nextInt();
int mat[][]=new int[row][col]; //giving matrix size
for(int i=0;i<row;i++)
{
for(int j=0;j<col;j++)
{
mat[i][j]=0; //or any value decided by you
}
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.