Task #4: Arrays, Methods and File I/O
In this task, you are being asked to write methods that manipulate arrays, and write and read to
and from the text file in Java.
1. Write a method called getSecondSmallestNumber that accepts an integer array as
argument and returns the second smallest number from the array.
You may use the following header for this method:
static int getSecondSmallestNumber(int[] array)
For example, if we pass {10, 17, 3, 5, 12, 19} then the method should return 5
as the second smallest number from the array.
class App {
static int getSecondSmallestNumber(int[] array) {
int temp;
for (int i = 0; i < array.length; i++) {
for (int j = i + 1; j < array.length; j++) {
if (array[i] < array[j]) {
temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
}
return array[array.length - 2];
}
public static void main(String[] args) {
int array[] = { 10, 17, 3, 5, 12, 19 };
int secondSmallestNumber = getSecondSmallestNumber(array);
System.out.print(secondSmallestNumber);
}
}
Comments
Leave a comment