Ask user to enter a positive integer number the integer n mu
Ask user to enter a positive integer number (the integer, n, must be under 20). Read n numbers and save them in array. Write four functions which accept as a parameter that array and return:
a. The average of positive numbers stored in the array.
b. The sum of elements with even indexes.
c. The maximum of the numbers stored in the array.
d. The index of the minimum of the numbers stored in the array.
Solution
NumberCalc.java
import java.util.InputMismatchException;
import java.util.Scanner;
public class NumberCalc {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print(\"Enter a positive integer number: \");
int n = scan.nextInt();
if(n < 0 || n > 20){
System.out.println(\"Invalid number. Number must be between 1 and 20.\");
}
else{
int a[]= new int[n];
for(int i=0; i<a.length; i++){
try{
System.out.print(\"Enter a positive number #\"+(i+1)+\": \");
a[i] = scan.nextInt();
}catch(InputMismatchException e){
i--;
System.out.print(\"Invalid number. \");
scan.nextLine();
}
}
System.out.println(\"The average of positive numbers stored in the array: \"+positiveNumberAverage(a));
System.out.println(\"The sum of elements with even indexes: \"+evenIndexSum(a));
System.out.println(\"The maximum of the numbers stored in the array: \"+maxNumber(a));
System.out.println(\"The index of the minimum of the numbers stored in the array: \"+minIndex(a));
}
}
public static double positiveNumberAverage(int[] a){
int sum = 0;
int count = 0;
for(int i=0; i<a.length; i++){
if(a[i] > 0){
sum = sum + a[i];
count++;
}
}
return sum/(double)count;
}
public static int evenIndexSum(int[] a){
int sum = 0;
for(int i=0; i<a.length; i=i+2){
sum = sum + a[i];
}
return sum;
}
public static int maxNumber(int[] a){
int max = a[0];
for(int i=0; i<a.length; i++){
if(max < a[i]){
max = a[i];
}
}
return max;
}
public static int minIndex(int[] a){
int min = a[0];
int minIndex = 0;
for(int i=0; i<a.length; i++){
if(min > a[i]){
min = a[i];
minIndex = i;
}
}
return minIndex;
}
}
Output:
Enter a positive integer number: 10
Enter a positive number #1: 2
Enter a positive number #2: a
Invalid number. Enter a positive number #2: 5
Enter a positive number #3: 6
Enter a positive number #4: -4
Enter a positive number #5: -5
Enter a positive number #6: -7
Enter a positive number #7: 8
Enter a positive number #8: 9
Enter a positive number #9: 1
Enter a positive number #10: 2
The average of positive numbers stored in the array: 4.714285714285714
The sum of elements with even indexes: 12
The maximum of the numbers stored in the array: 9
The index of the minimum of the numbers stored in the array: 5

