Page 8
Task #8: Using Arrays and Methods
In this task, you are being asked to write methods that manipulate arrays in Java.
Write a method called fillArray() which will take an integer array as input and the fills the array
with the user entered numbers.
You may use the following header for this method:
static void fillArray(int[] array)
Write a method called absoluteArray() which will take an integer array as input and takes the
absolute of all the array elements.
You may use the following header for this method:
static void absoluteArray(int[] array)
Take a number from the user as the size of the array, call the method fillArray(), then call the
method absoluteArray().
NOTE: Perform input validation so that the array size must be greater than 0.
1. Create a program called ArrayAbsoluteLab1.java.
2. Create appropriate variables and assign values using a Scanner object.
3. Correctly display appropriate messages.
import java.util.InputMismatchException;
import java.util.Scanner;
public class ArrayAbsoluteLab1 {
private static void fillArray(int[] array) {
Scanner input = new Scanner(System.in);
System.out.println("Enter " + array.length + " numbers to fill array:");
for (int i = 0; i < array.length; i++) {
while (true) {
try {
array[i] = input.nextInt();
break;
} catch (InputMismatchException e) {
System.out.println("The entered number is incorrect, please try again...");
input.next();
}
}
}
}
private static void absoluteArray(int[] array) {
for (int i = 0; i < array.length; i++) {
System.out.println("Absolute value of number " + array[i] + " is " + Math.abs(array[i]));
}
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int arrayLength;
System.out.println("Enter array length:");
while (true) {
try {
arrayLength = input.nextInt();
if (arrayLength <= 0) {
System.out.println("The entered array length is incorrect, please try again...");
continue;
}
break;
} catch (InputMismatchException e) {
System.out.println("The entered array length is incorrect, please try again...");
input.next();
}
}
int array[] = new int[arrayLength];
fillArray(array);
absoluteArray(array);
}
}
Comments
Leave a comment