-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathSingleDimensionalArray.java
61 lines (50 loc) · 1.58 KB
/
SingleDimensionalArray.java
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
public class SingleDimensionalArray {
int arr[] = null;
public SingleDimensionalArray(int sizeOfArray) {
arr = new int[sizeOfArray];
for (int i=0; i<arr.length; i++) {
arr[i] = Integer.MIN_VALUE;
}
}
public void insert(int location, int valueToBeInserted) {
try {
if (arr[location] == Integer.MIN_VALUE) {
arr[location] = valueToBeInserted;
System.out.println("Successfully inserted");
} else {
System.out.println("This cell is already occupied");
}
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Invalid index to access array!");
}
}
// Array Traversal
public void traverseArray() {
try {
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
} catch (Exception e) {
System.out.println("Array no longer exists!");
}
}
//Search for an element in the given Array
public void searchInArray(int valueToSearch) {
for (int i = 0; i < arr.length; i++) {
if (arr[i] == valueToSearch) {
System.out.println("Value is found at the index of " + i);
return;
}
}
System.out.println(valueToSearch + " is not found");
}
// Delete value from Array
public void deleteValue(int valueToDeleteIndex) {
try {
arr[valueToDeleteIndex] = Integer.MIN_VALUE;
System.out.println("The value has been deleted successfully");
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("The value that is provided is not in the range of array");
}
}
}