Java - 计算整数在矩阵中出现的次数

时间:2014-05-28 14:03:48

标签: java matrix

我需要找到某个整数出现在矩阵中的次数,无论我做什么,我得到的结果总是" 0"。最有可能的答案很简单,但我无法找到它,我会感激一些帮助。 :)

这是我的代码:

    int m, n, c, d, nr = 0, x;
    Scanner in = new Scanner(System.in);

    System.out.println("Enter the number of rows:");
    m = in.nextInt();
    System.out.println("Enter the number of columns:");
    n  = in.nextInt();

    int matrix[][] = new int[m][n];

    System.out.println("Enter the elements of the matrix:");

    for (  c = 0 ; c < m ; c++ )
        for ( d = 0 ; d < n ; d++ )
            matrix[c][d] = in.nextInt();

    System.out.println("Enter the value for number x:");
    x = in.nextInt();

    for (  c = 0 ; c < m ; c++ ) {
        if(c == x)
            nr++;
    }

    for ( d = 0 ; d < n ; d++ ) {
        if(d == x)
            nr++;
    }

    System.out.println("Number x appears " + nr + " times.");`

P.S。我对Java很陌生。

6 个答案:

答案 0 :(得分:5)

您没有将matricex进行比较。

您正在将x与索引进行比较。

而是试试这个:

for (  c = 0 ; c < m ; c++ ) {
    for(d = 0; d < n; d++) {
        if(x == matrice[c][d]) {
            nr++;
        }
    }
}
System.out.println("Number x appears " + nr + " times.");`

答案 1 :(得分:3)

您需要像这样检查矩阵的值

for (  c = 0 ; c < m ; c++ ) {
    for ( d = 0 ; d < n ; d++ ) {
        if(matrix[c][d] == x)
            nr++;
    }
}

答案 2 :(得分:2)

你应该写:

int m,n,c,d,nr = 0,x;     Scanner in = new Scanner(System.in);

System.out.println("Enter the number of rows:");
m = in.nextInt();
System.out.println("Enter the number of columns:");
n  = in.nextInt();

int matrix[][] = new int[m][n];

System.out.println("Enter the elements of the matrix:");

for (  c = 0 ; c < m ; c++ )
    for ( d = 0 ; d < n ; d++ )
        matrix[c][d] = in.nextInt();

System.out.println("Enter the value for number x:");
x = in.nextInt();

//MODIFY THIS:

for (  c = 0 ; c < m ; c++ )
    for ( d = 0 ; d < n ; d++ )
        if (matrix[c][d] ==x)
              nr++;


System.out.println("Number x appears " + nr + " times.");`

原因是你要传递矩阵中的所有单元格并检查它们中的哪一个等于x。

答案 3 :(得分:1)

您必须测试矩阵的内容,而不是索引:

for (int r = 0; r < matrix.length; ++r)
{
    for (int c = 0; c < matrix.length; ++c)
    {
        if (matrix[r][c] == x)
        {
            counter++;
        }
    }
}

答案 4 :(得分:0)

你想做一个嵌套的设置,比如

for(small to large x){
   for(small to large y){
      if(matrix[x][y] == integer looking for)
          count = count + 1; }}

这将在您输入后完成。

答案 5 :(得分:0)

尝试

    for (  c = 0 ; c < matrix.length ; c++ ) {
         for ( d = 0 ; d < matrix[c].length ; d++ ) {
                if(matrix[c][d] == x)
                    nr++;
            }

    }