Write a program that does the following: Declare a 2 dimensional array of ints t
ID: 3662635 • Letter: W
Question
Write a program that does the following:
Declare a 2 dimensional array of ints that is 3 rows and 3 columns. Fill the array up with numbers between 1 and 9. There is no user input. You can just copy/paste these lines:
int[][] table1 = { { 3, 2, 5}, {1,9,6}, {7, 8 4} }; // this one is true
int[][] table2 = { { 3, 3, 5}, {1,9,6}, {3, 8 4} }; // this one is false
int[][] table3 = { { 3, 2, 5}, {1,9,6}, {3, 8 4} }; // this one is false
int[][] table4 = { { 3, 2, 1}, {10,4,6}, {5,7,8} }; // this one is false
int[][] table5 = { { 4, 1, 5}, {1,9,6}, {7, 8 4} }; // this one is false
Write a static method that will check to see if the array contains all of the numbers 1 through 9. (Each must appear one time only.) Pass the array to the method. The method must return a boolean, true if all the numbers appear in the array, and false otherwise.
calling your method should look like this:
if( allNinePresent(table1)) {
syso( “All 9 are there in table 1”);
} else {
Syso(“ All 9 are NOT there in table 1 “);
}
============================
Your method header should look like this:
private static boolean allNinePresent(int[][] array){
========================
There are many strategies for solving this. You can choose whatever one makes most sense for you. Here are a few options.
Write a method that converts the 2d array to a 1d array. That’s easier to work with. Sort the 1d array, then loop through looking for the numbers 1-9.
OR
This is my favorite. Write a method that returns a boolean. It will take a number and a 2d array. static boolean contains(int a, int[][] array) It returns true if ‘a’ is found in the array. You can call that method 9 times, to verify that each number 1 – 9 is in the array.
OR
Make a loop that looks for each of the numbers from 1-9. When one of them is not found, return false. After all are found return true.
OR
Use one of the Collection classes, and the contains() methods to see if they are all there.
Explanation / Answer
Program:
public class AllNumber {
static boolean allNinePresent(int table[][])
{
int[] arr=new int[9];
for(int i=0;i<9;i++)
arr[i]=0;
for(int i=0;i<3;i++)
for(int j=0;j<3;j++)
arr[table[i][j]-1]=1;
for(int i=0;i<9;i++)
if(arr[i]==0)
return false;
return true;
}
public static void main(String arg[])
{
int[][] table1 = { { 3, 3, 5}, {1,9,6}, {3, 8 ,4} }; // this one is true
if( allNinePresent(table1)) {
System.out.println("All 9 are there in table 1");
} else {
System.out.println("All 9 are NOT there in table 1");
}
}
}
Result:
All 9 are NOT there in table 1
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.