-
Notifications
You must be signed in to change notification settings - Fork 0
/
MultidimentionalArray
79 lines (64 loc) · 2.07 KB
/
MultidimentionalArray
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
public class TwoDimensionalArray {
int arr[][] = null;
// Constructor
public TwoDimensionalArray(int numberOfRows, int numberOfColumns) {
this.arr = new int[numberOfRows][numberOfColumns];
for (int row = 0; row < arr.length; row++) {
for (int col = 0; col < arr[0].length; col++) {
arr[row][col] = Integer.MIN_VALUE;
}
}
}
// Inserting value in the Array
public void insertValueInTheArray(int row, int col, int value) {
try {
if (arr[row][col] == Integer.MIN_VALUE) {
arr[row][col] = value;
System.out.println("The value is successfully inserted");
} else {
System.out.println("This cell is already occupied");
}
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Invalid index for 2D array");
}
}
// Accessing cell value from given array
public void accessCell(int row, int col) {
System.out.println("\nAccessing Row#" + row + ", Col#" + col);
try {
System.out.println("Cell value is: " + arr[row][col]);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Invalid index for 2D array");
}
}
// Traverse 2D array
public void traverse2DArray() {
for (int row=0; row < arr.length; row++) {
for (int col=0; col < arr[0].length; col++) {
System.out.print(arr[row][col] + " ");
}
System.out.println();
}
}
// Searching a single value from the Array
public void searchingValue(int value) {
for (int row=0; row<arr.length; row++){
for (int col=0; col<arr[0].length; col++) {
if (arr[row][col] == value) {
System.out.println("Value is found at row: "+ row + " Col: " + col);
return;
}
}
}
System.out.println("Value is not found");
}
// Deleting a value from Array
public void deleteValuefromArray(int row, int col) {
try {
System.out.println("Successfully deleted: " + arr[row][col]);
arr[row][col] = Integer.MIN_VALUE;
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("This index is not valid for array");
}
}
}