gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 11:44:10 25 4
gpt4 key购买 nike

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

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

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com