java - 检查一个数字是否在二维数组中,并打印它所在的行

标签 java arrays multidimensional-array

我正在尝试编写一个程序,允许用户将某个二维数组乘以他们声明的整数。然后允许用户检查任何数字并查看它是否在相乘的二维数组中。如果该数字位于相乘的二维数组中,则仅打印它所在的行。

这是我到目前为止的代码:

import java.util.Arrays;
import java.util.Scanner;

public class QD {

public static void main(String[] args) {

    // Prompts users to choose to number to multiply by

    Scanner z = new Scanner (System.in);
    System.out.print("Enter a number to multiply the elements in the array by: ");
    int y = z.nextInt();

    // creates a 2D array specific in the question

    int [][] arr = {{1, 2*y, 3*y, 4*y}, {5*y, 6*y, 7*y, 8*y}, {9*y, 10*y, 11*y, 12*y}};
    System.out.println(Arrays.deepToString(arr)); // Prints 2D array

    // Prompts user to choose a number to check in the array

    Scanner p = new Scanner (System.in);
    System.out.print("Enter to see if it's in the array: ");
    int r = p.nextInt();

    if (Arrays.asList(arr).contains(r))
        System.out.println("This number is in the 2D array");
    else
        System.out.println("This number is not in the 2D array");       

}

}

当我选择 1 来乘以数组时,数字 3 就在数组中。但是,当我检查数组中是否有 3 时,它输出“这个数字不在 2D 数组中”为什么要这样做?如果用户在数组中找到数字,我也很难找到仅打印一行的方法。有什么指点吗?

最佳答案

遍历数组来搜索给定的数字searchingNumber。您可以考虑使用 for 循环。通过使用 for 循环,您可以返回行号 -

int found = -1 //means searchingNumber has not found anywhere in array[][]

    for(int row = 0; row<highestRowCount; row++){ 
     for(int column = 0; column<highestColumnCount; coumn++){

       if(if array[row][column] == searchingNumber){
         found = row+1;
         break;
       }

     }
    }

现在变量 found 包含找到 searchingNumber 的行号。如果 found 为 -1,则表示在 array[][]

中未找到您的 searchingNumber

关于java - 检查一个数字是否在二维数组中,并打印它所在的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29289632/

相关文章:

java - 数组,无法理解如何设置它

java - 配置 Liberty Profile 以使用 H2 数据库

java - 从同一个文件java读取字符串和字节

php - 在 PHP 中从 MySQL 表创建多维数组树

java - 如何在不知道尺寸的情况下使用从文件中获取的数据加载 Java 中的 N_by_M 矩阵?

java - 在 Java 中有效检测损坏的 url

ios - Swift2 的数组

javascript - 如何访问和处理嵌套对象,数组或JSON?

c++ - 数组下标的无效类型 'double [100][double]'

php - 获取最深嵌套的数组