
Patrick B. answered 08/25/19
Math and computer tutor/teacher
It sounds like you want to randomly access the elements of the 2 x 2 array.....
you need to generate TWO random indices. Here is some code. You can run it
as many times as you want. It took several times, but index (1,1) did come out..
import java.io.*;
class Array2D
{
public static void main(String args[])
{
int N=2;
int [][] A;
int [] b1 = {1,2};
int [] b2 = {2,3};
A= new int [2][2];
A[0] = new int[2];
A[1] = new int[2];
A[0] = b1;
A[1] = b2;
boolean done_flag = false;
Console console = System.console();
while (!done_flag)
{
/************************************************
//generates a random number between 1 and 100;
// if less than 50, random index is zero;
// otherwise it is ONE (1)
****************************************************/
double randomNum = Math.random() * 99+1;
int randIndex1 = (randomNum<50) ? 1 : 0;
randomNum = Math.random() * 99+1;
int randIndex2 = (randomNum<50) ? 1 : 0;
System.out.println(" random index 1 = " + randIndex1);
System.out.println(" random index 2 = " + randIndex2);
System.out.println(" the array element is " + A[randIndex1][randIndex2]);
try
{
System.out.print(" Do It again ???? input 1 = Yes 0 = No :> ");
String inbuff = console.readLine();
int response = Integer.parseInt(inbuff);
done_flag = (response==0) ? true : false;
}
catch (Exception ex) { System.err.println(" input error "); continue; };
} //while
} //main
} //class
Pranav B.
Thank you Sir for your answer but I am looking for a more simplified and generalized program. Instead of using for (p:a3[r]) loop what can I do to store the value of array a3( indexed 'r' )into another array.08/26/19