The objective is to make an array of size 100, have a user enter a bunch of positive numbers, and quit whenever they enter -1 (or fill up 100 spots I guess). After that, print out the number of inputs read in, the average value, and highest value. I was testing my code with a smaller sized array originally to get the average and now realize that array.length isn't what I'm looking for as I switch it to 100 and don't fill up 100 slots. My question is, how can I count the amount of input thats been entered into an array and not just the total length of an array?
import java.util.*;
class Array{
public static void main(String [] args){
Scanner scan = new Scanner(System.in);
int[] array = new int[100];
System.out.println("Enter your number: ");
for(int i = 0; i < 100; i++){
int entry = scan.nextInt();
if(entry == -1){
System.out.println("Goodbye.");
i--;
break;
}else if(entry < -1){
System.out.println("Invalid.");
i--;
}else{
array[i] = entry;
}
}
//prints amount of elements inside array
//System.out.println("There are " + countArray(array) + " numbers in this array.");
//prints average
System.out.println("The average is: " + findAverage(array));
//prints highest val
System.out.println("The highest value is: " + findHigh(array));
}
//public static int countArray(int[] array)
//need help here and then fixing the issue in the average method
public static double findAverage(int [] array){
double sum = 0;
for(int i = 0; i < array.length; i++){
sum += array[i];
}
double average = (sum/array.length);
return average;
}
public static int findHigh(int[]array){
int max = array[0];
for(int i = 1; i < array.length; i++){
if (array[i] > max){
max = array[i];
}
}
return max;
}
}
Aucun commentaire:
Enregistrer un commentaire