Reputation: 5
I'm trying to make a program to allow users to multiply a certain 2D array by a integer they declare. Then allow the user to check any number and see if it's in the multiplied 2D array. If that number is in the multiplied 2D array, print ONLY the row that it's in.
Here's my code so far:
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");
}
}
When I choose 1 to multiply the array the number 3 is in the array. However when I check if 3's in the array, it outputs "this number is not in the 2D array" Why is it doing this? And I'm also having trouble finding a way to print only a row if the user finds the number in the array. Any pointers?
Upvotes: 0
Views: 1486
Reputation: 11173
Traverse the array to search your given number searchingNumber
. You may consider using of for loop. By using for loop you may return the row number -
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;
}
}
}
Now the variable found
contains row number at where your searchingNumber
was found. If found
is -1 that means your searchingNumber
is not found in your array[][]
Upvotes: 1