0

为什么我的代码中出现错误 - 我创建了两种方法,randomGen 生成随机数,matrixGen 使用随机数创建矩阵。我收到不兼容的类型错误。如果有人可以请指出我可能做错的正确方向..我仍处于学习阶段..这是我的代码:

import java.util.Random;

public class sparse{
    static int matrix [][] = new int[6][6];

    public static int randomGen(){
        int rA;
        Random r = new Random();
        rA = r.nextInt(100);
        return rA;
    }

    public static int[][] matrixGen(){
        for(int i=0; matrix[i].length < i; i++){
            for(int j=0; matrix[j].length <j; j++){
                matrix[i] = matrix[i].randomGen();
                matrix[j] = matrix[j].randomGen();
            }
        }
        return matrix[i][j];
    }

    public static void main(String args[]){
        new sparse();
    }
}
4

4 回答 4

7

Get rid of randomGen, use this:

public static int[][] matrixGen(){
    Random r = new Random( );
    for(int i=0; i < matrix.length; i++){
        for(int j=0; j < matrix[i].length; j++){
            matrix[i][j] = r.nextInt( 100 );
        }
    }
    return matrix;
}

3 (update: 4) things:

  1. you're using Random wrong. You should create it once, then get lots of numbers from it.
  2. you're trying to call randomGen on an int, which makes no sense; it's a property of sparse, not int. You could have done matrix[i][j] = randomGen().
  3. you're doing something very odd indeed to access array elements. Hopefully this code will clear it up for you a bit.
  4. your loops are odd too. I've fixed them in this snippet.
于 2013-03-09T00:09:24.747 回答
1

这个:

    matrix[i] = matrix[i].randomGen();
    matrix[j] = matrix[j].randomGen();

需要是这样的:

    matrix[i][j] = randomGen();
于 2013-03-09T00:10:54.960 回答
0

你的matrixGen方法很混乱。您的外部ifor 循环在达到数组长度时需要停止迭代matrix,而不是第一个i内部数组的长度。同样,您的内部jfor 循环需要在达到matrix[i]数组长度时停止迭代。

如果您想为二维数组中的一个特定位置分配一个值,那么您需要一个分配,而不是两个;在左侧,=您需要同时使用 ij

您不需要在调用之前添加matrix[i]or ,因为您在同一个类中定义了它。matrix[j]randomGen

您甚至没有调用该matrixGen方法。

于 2013-03-09T00:11:10.120 回答
0

首先,在提供的代码中,你main什么都不做,因为你创建了一个你不使用的对象。我认为它会在未来继续。

至于您遇到的错误,我还必须做出假设,因为没有提供其他信息。

您遇到的错误可能在您的matrixGen方法中,我认为该方法应该填充静态矩阵。它应该是这样的:

public static void matrixGen(){
    for(int i=0; i < matrix.length; i++){
        for(int j=0; j < matrix[i].length; j++){
            matrix[i][j] = randomGen();
        }
    }
}
  1. void,因为你正在修改你的矩阵,而不是创建一个新的;
  2. 您的循环条件错误。索引会递增,直到它们达到各自的长度(i对于行和j列);
  3. 使用两个索引(行和列)访问矩阵单元;
  4. randomGen是来自 的方法class sparse,而不是来自数组的方法。

编辑:正如戴夫所指出的,您不应该Random每次都创建一个新实例。将 存储Random在一个变量中,就像您对矩阵所做的那样,或者在进入循环之前以相同的方法创建它。

于 2013-03-09T00:14:42.243 回答