Allocate storage to store a 3 row by 3 column two dimensional array of integers.
ID: 3840885 • Letter: A
Question
Allocate storage to store a 3 row by 3 column two dimensional array of integers. Call the array A. Initialize the array with each element’s value as follows: A[0][0] = 1 A[0][1] = 2 A[0][2] = 3 A[1][0] = 4 A[1][1] = 5 A[1][2] = 6 A[2][0] = 7 A[2][1] = 8 A[2][2] = 9 Then, have the program use a loop to continually ask the user to input a pair of integers. The first integer is the row number (row) and the second integer is the column number (column) of an element in the array A. One of these three actions will be performed depending on the value of the row number and column number inputted: 1. If the row number is -1 and the column number is -1 then terminate the loop and the program. 2. Or, check to make sure the row number and column number are valid indices for the array A. A valid index for array A is 0, 1 or 2. If either the row number or the column number (or both) are invalid then do nothing and return to the beginning of the loop to ask for a new pair of numbers. 3. If the row number and the column number are valid indices then load the value of element A[row][column] from memory and print out the value. Then, return to the beginning of the loop to ask for a new pair of numbers.
Explanation / Answer
TwoDArray.java
import java.util.Scanner;
public class TwoDArray {
public static void main(String[] args) {
//Declaring variables
int row,col;
//Creating an Two Dimensional Array
int A[][]=new int[3][3];
A[0][0] = 1;
A[0][1] = 2;
A[0][2] = 3;
A[1][0] = 4;
A[1][1] = 5;
A[1][2] = 6;
A[2][0] = 7;
A[2][1] = 8;
A[2][2] = 9;
//Scanner object is used to get the inputs entered by the user
Scanner sc=new Scanner(System.in);
/* This loop continues to execute until the user
* enters a valid row and column index value
*/
while(true)
{
//Getting the inputs entered by the user
System.out.print("Enter the row and column Index :");
row=sc.nextInt();
col=sc.nextInt();
if(row==-1 && col==-1)
{
System.out.println(":: PROGRAM EXIT ::");
break;
}
else if((row<0 || row>2) ||(col<0 || col>2) )
{
continue;
}
else
{
System.out.println(A[row][col]);
break;
}
}
}
}
______________________________
Output#1:
Enter the row and column Index :-1 -1
:: PROGRAM EXIT ::
__________________________
Output#2:
Enter the row and column Index :5 7
Enter the row and column Index :-1 4
Enter the row and column Index :2 -1
Enter the row and column Index :2 1
8
________________Thank YOu
Plz Rate me well,
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.