Convert int array into a bunch of ints - java

I have
public int average(int grades[]){return **}
and I call it with: average({80, 90, 100})
I want to separate the array into three individual ints.

public int average1 = average[0];
public int average2 = average[1];
public int average3 = average[2];
Hope i helped :)
Edit: Whoops forgot to put a semicolon xD

If you're looking to compute the average of several integers in your grades array, as is implied by the name of your method, and regardless of how many items are in the array, you can use Java 8 streams. Just a suggestion.
public int average(int[] grades)
{
OptionalDouble od = Arrays.stream(grades).average();
if(od.isPresent())
{
return (int)od.getAsDouble();
}
return 0; //error condition to be checked by calling method.
}

The fact that the data is in an array, you already have "n" individual ints. Each element of the array is an individual int that you can access via an index value ranging from 0 to (n - 1), where n is the length of the array.
So an array of 3 ints would have indices 0, 1, 2.
With that, if your average() is to compute the average of the ints you have in your array, just loop through your array and accumulate the values into a sum and divide that sum by the number of ints that you have.
public static void main(String[] args) throws Exception {
System.out.println("Average: " + average(new int[] {80, 90, 100}));
}
public static int average(int[] grades) {
int sum = 0;
for (int i = 0; i < grades.length; i++) {
sum += grades[i];
}
return sum / grades.length;
}
Results:
Average: 90

Related

finding the sum of an arraylist but excluding the largest element [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I currently don't have any code , but I need to return the sum of an arraylist but without including the largest element, for example , 3,4,5,10, I would have to find the sum of 3+4+5 which =12.
I have no idea how to write the code so that it ignores the largest element.
I've currently got :
int sum = 0;
for(int i = 0; i < array.length; i++)
sum = sum + array[i];
return sum;
I this problem as a simple combination of two problems:
Sum all the elements of a collection
Find the largest element in a collection
You could probably do both in a single iteration over your collection:
sum elements one by one, keep track of the highest so far
once done, subtract the highest to the total sum
But there are many other ways as stated in comments or answers; just find the one you think fits the most your logic.
Approach
Compute the full sum, then compute the max element and subtract it from the full sum:
List<Integer> values = List.of(3, 4, 5, 10);
int sum = 0;
for (int value : values) {
sum += value;
}
int max = Collections.max(values);
sum -= max;
Single iteration
You can of course also compute both in one go:
List<Integer> values = List.of(3, 4, 5, 10);
int sum = 0;
int max = values.get(0);
for (int value : values) {
sum += value;
if (value > max) {
max = value;
}
}
sum -= max;
Streams
And you can also use the Stream API to do the job. IntStream::summaryStatistics computes everything needed efficiently in one go:
List<Integer> values = List.of(3, 4, 5, 10);
IntSummaryStatistics stats = values.stream()
.mapToInt(Integer::intValue)
.summaryStatistics();
int sum = stats.getSum() - stats.getMax();
Also very helpful if you have a very large list of data (> 10k) as it provides multithreading out of the box.
import java.util.Arrays;
public class Sum {
public static void main(String[] args)
{
// TODO Auto-generated method stub
//arr size>1
int arr[] = {3,5,4};
int res[] = getSumAndMax(arr);
int sum=0;
Arrays.sort(arr);
for(int i=0;i<arr.length-1;i++)
{
sum+=arr[i];
}
System.out.println("sum="+sum+" :max="+arr[arr.length-1]);
System.out.println("sum="+res[0]+" :max="+res[1]);
}
public static int[] getSumAndMax(int[] arr)
{
int sum=0;
int max=arr[0];
for(int i=0;i<arr.length;i++)
{
sum+=arr[i];
max = Math.max(max, arr[i]);
}
int out[] = {sum-max, max};
return out;
}
}
Output:
sum=7 :max=5
Try this.
set sum and max to first value.
then iterate and compute sum and find max.
then return sum less the value max.
public static int findSum(int[] array) {
if (array == null || array.length <2){
return 0;
}
int max = array[0];
int sum = max;
for (int i = 1; i < array.length; i++) {
int v = array[i];
sum = sum + v;
if (v > max) {
max = v;
}
}
return sum - max;
}
And here is a way to do it with streams.
stream the ints
invert the bits (complement operator ~)
sort them
skip the first one
invert them again
sum.
The inverting of the bits is an old trick that allows them to be sorted in equivalent reverse order since an IntStream sorted method does not take a Comparator. Then skip the first element which would be the largest, invert them again to their original value and then sum the remainder.
public static int findSumStream(int[] array) {
return array == null || array.length < 2 ? 0 : Arrays
.stream(array)
.map(i -> ~i)
.sorted()
.map(i->~i)
.skip(1)
.sum();
}

Java program calculates average of variable array, input from command line, displays results

Below is what I have so far. The instructions are to create a simple java program that calculates the avg of a variable quantity of ints. Args array for main, no Scanner object, find and display highest and lowest value. Static method that takes user input as argument & returns values. Should display welcome message at launch.
So I think the start of my code is correct! It compiles for me. But I'm not sure how to get user input w/o scanner. I assume I need to use an array in the static method to translate the input into an argument. Which at execution would be java CalculateAverage 1, 2, 5, 9, 20?
And then would I call MATH? So I can display all the values of min max & avg? Am I on the right track..? The questions are specific in the code. Sorry, first time posting here!
public class CalculateAverage {
public static void main(String[] args) {
System.out.print("Hello welcome to the Average Calculator");
int[] array = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int a = Integer.parseInt(args[0]);
int b = Integer.parseInt(args[1]);
//do i just keep going and adding letters til j?
//or is there an easier way to do this..?
minArray(array);
maxArray(array);
sumArray(array);
avgArray(array);
}
public static double maxArray(double[] array){
double max = Double.NEGATIVE_INFINITY;
//tbh i saw this on a tutorial, idk if NEGATIVE_INFINITY would
//work for me?
for (int i = 0; i < n; i++)
if (array[i] > max) max = array[i];
System.out.println("The maximum of your array is:" + max);
}
public static double avgArray(double[] array){
double sum = 0.0;
for(int i = 0; i < n; i++)
sum += array[i];
double avg = sum / n;
System.out.println("The average value of your array is: " + avg);
} //then i would make another static for the min but probably before max
}
From the command line, you want to execute
javac CalculateAverage.java
to have Java compile the class and prepare to run it. Then you can execute the code with
java CalculateAverage arg0 arg1 arg2 ...
Now, in your main( string[] args ) method, I see you're creating an array with 11 elements. This is not necessary, and it is not ideal - what if the user gives more than 11 arguments when they're running the program? The better way to do this is:
int[] array = new int[ args.length ]()
This creates a new array of ints, of the same length as the array args - every array has that property length that states how many elements the array has. Now, we haven't actually put anything in array yet, but we know that it has space for the same number of arguments as the program gave. Now, to initialize each element:
for(int i = 0; i < args.length; i++) {
array[i] = Integer.parseInt(args[i])
}
A for loop creates a variable i (this is the int i = 0 part), initialized to 0, and then executes the code inside the curly brackets. After it's done, it increases the value of i by one (this is the i++ part), and runs the code inside the curly brackets again, continuously, until the condition i < args.length is false. Altogether, this iterates through every element of args and initializes the corresponding element of array.
Now, you could use the Math module to do the calculations for you, but you're almost there in doing it yourself. Here's a slight touch-up to maxArray, for example:
public static int maxarray(int[] array) {
int max = array[0]
for (int i = 1; i < array.length; i++) {
if (array[i] > max) max = array[i];
}
}
System.out.println("The maximum of your array is:" + max);
}
I'm using int here because the inputs were ints. In general you should probably make sure that everything is the same type of variable; either make all the numbers ints or make them all doubles, but don't try to go back and forth between them.
You don't actually need negative infinity for anything; you can just start with the first number in your array, call that the maximum, and then for every number afterwards, replace the maximum if it's larger. We use the for loop in the same way here, to iterate over the entire array.
Similarly, you're doing avgArray(double[] array) correctly already - except that I don't know where you got the variable n from (you should be using array.length again).
Overall, I recommend looking back over your notes for this class so far, and carefully make sure you know what everything means and how it applies to this example. Review what you've been taught about how Arrays work; and about the differences between ints and doubles.
This is what I would do. Hopefully the code is simple and self-explanatory but let me know if any questions:
public static void main(String[] args) {
System.out.println("Hello welcome to the Average Calculator");
int numArgs = args.length; //Since args is an array we can get the number of elements with .length
int min = Integer.MAX_VALUE; //The maximum possible value an int can be
int max = Integer.MIN_VALUE; //The minimum possible value an int can be
double total = 0;
for(int i = 0; i < numArgs; i++) {
int nextI = Integer.parseInt(args[i]);
total += nextI;
if(nextI < min) {
min = nextI;
}
if(nextI > max) {
max = nextI;
}
}
System.out.println("The average is: " + total/numArgs);
System.out.println("The min is: " + min);
System.out.println("The max is: " + max);
}
Then, you would run the code like this:
java CalculateAverages 1 2 3 4 5 6 7 8 9
Hello welcome to the Average Calculator
The average is: 5.0
The min is: 1
The max is: 9
Edit:
The instructions said "To find these value, make static methods that
take the user input as arguments & returns the value"
public static void main(String[] args) {
int numArgs = args.length;
int[] userIntInputs = new int[numArgs];
for(int i = 0; i < numArgs; i++) {
userIntInputs[i] = Integer.parseInt(args[i]);
}
System.out.println("The average is: " + getInputAverage(userIntInputs));
System.out.println("The min is: " + getInputMin(userIntInputs));
System.out.println("The max is: " + getInputMax(userIntInputs));
}
private static int getInputMax(int[] userIntInputs) {
int max = Integer.MIN_VALUE;
for(int i = 0; i < userIntInputs.length; i++) {
if(userIntInputs[i] > max) {
max = userIntInputs[i];
}
}
return max;
}
private static int getInputMin(int[] userIntInputs) {
int min = Integer.MAX_VALUE;
for(int i = 0; i < userIntInputs.length; i++) {
if(userIntInputs[i] < min) {
min = userIntInputs[i];
}
}
return min;
}
private static double getInputAverage(int[] userIntInputs) {
double total = 0;
for(int i = 0; i < userIntInputs.length; i++) {
total += userIntInputs[i];
}
return total/userIntInputs.length;
}
One Method Alternative
Idk if she means to make a method for each value or one method!
Yeah teachers can be confusing all right. Here's a one method approach...
public static void main(String[] args) {
int numArgs = args.length;
int[] userIntInputs = new int[numArgs];
for(int i = 0; i < numArgs; i++) {
userIntInputs[i] = Integer.parseInt(args[i]);
}
Object[] inputMetrics = getInputMetrics(userIntInputs);
System.out.println("The average is: " + inputMetrics[0]);
System.out.println("The min is: " + inputMetrics[1]);
System.out.println("The max is: " + inputMetrics[2]);
}
private static Object[] getInputMetrics(int[] userIntInputs) {
int min = Integer.MAX_VALUE;
int max = Integer.MIN_VALUE;
double total = 0;
for(int i = 0; i < userIntInputs.length; i++) {
int nextI = userIntInputs[i];
total += nextI;
if(nextI < min) {
min = nextI;
}
if(nextI > max) {
max = nextI;
}
}
Object[] metrics = {total/userIntInputs.length, min, max};
return metrics;
}
Simplicity is IMHO the best way. This does the whole thing:
DoubleSummaryStatistics stats = Arrays.stream(args)
.collect(Collectors.summarizingDouble(Double::parseDouble));
System.out.println("The minimum of your array is: "+ stats.getMin());
System.out.println("The maximum of your array is: "+ stats.getMax());
System.out.println("The sum of your array is: "+ stats.getSum());
System.out.println("The average of your array is: "+ stats.getAverage());
When there's a built-in library to handle something, use it.

Displaying Average Integer in Array using Driver Program

I need practice with my syntax. I have an array of numbers and with that are methods to find the average, report highest number, and report the lowest number. To report the highest/lowest numbers I will be sorting the array.
But first my problem is with reporting the average. I think that if I can understand that part, then the min/max will be no problem. I have tried changing it to say Driver.randomArray[].getAverage() as well.
Are there any suggestions? Thanks in advance.
~Crystal
error code:
Exception in thread "main" java.lang.Error: Unresolved compilation problems:
randomArray cannot be resolved to a type
Class cannot be resolved to a type
Syntax error, insert ". class" to complete Expression
at IntegerArray.main(IntegerArray.java:48)
and it refers to my attempt to call the average from this line,
System.out.println(randomArray[].getAverage());
First, Driver Class
import java.util.Arrays;
public class Driver {
private static final int MAX = 0;
public Driver(){
int[] randomArray = new int [MAX];
int sum;
final int MAX;
}
public int getAverage(){
for (int index = 0; index < MAX; index++){
int sum = 0;
int[] randomArray = null;
int average;
sum = sum + randomArray[index];
average = sum/MAX;
return average;}
}
public void sortArray(){
// sort the array from smallest to biggest
int[] randomArray;
Arrays.sort(randomArray);
System.out.println("The sorted array from smallest to biggest is:");
for (int number : randomArray) {
System.out.println( + number)}
}
public int getMin(){
int[] randomArray;
// find the lowest number
return randomArray[0];
}
public int getMax(){
int[] randomArray;
// find the highest number
return randomArray[MAX];
}
}
Then my main class:
import java.util.Random;
import java.lang.reflect.Array;
import java.util.Arrays;
public class IntegerArray {
public static void main (String[] args) {
// set up the constant for the size of the array
final int MAX = 10;
int sum = 0;
int average = 0;
int[] randomArray = new int [MAX];
for (int index = 0; index < MAX; index++)
// values of the array go from 0-10
randomArray[index] = (int) (Math.random() *10);
// prints the array
for (int value : randomArray)
System.out.println (value);
System.out.println("The length of the array is: " + randomArray.length);
System.out.println(randomArray[].getAverage());
}
}
The way you're creating your methods eg. getAverage() you can't call it on the array you created. On the other hand you can call them on the a Driver object you create. for example: Driver driver = new Driver(); System.out.println(driver.getAverage()); If you want to call them on the Array Object you should add them on the Array class (but that is something more advanced Java than this).
In Java Code you need to add a ; after a statement don't forget them ;). Your IDE should warn you about them.
When you create your getMax() method you should add the array as a parameter. So that the method knows for what Array object it should get the highest number. For example:
public int getMax(int[] randomArray) {
// find the highest number
return randomArray[MAX];
}
This counts for all your methods.
I hope this solves some of your answers if not please add a comment or something.
So here is your code after that:
Driver class:
import java.util.Arrays;
public class Driver {
private static final int MAX = 0;
public Driver() {
int[] randomArray = new int[MAX];
int sum;
final int MAX;
}
public int getAverage() {
int average = 0;
for (int index = 0; index < MAX; index++) {
int sum = 0;
int[] randomArray = null;
sum = sum + randomArray[index];
average = sum / MAX;
}
return average;
}
public void sortArray(int[] randomArray) {
// sort the array from smallest to biggest
Arrays.sort(randomArray);
System.out.println("The sorted array from smallest to biggest is:");
for (int number : randomArray) {
System.out.println(+number);
}
}
public int getMin(int[] randomArray) {
// find the lowest number
return randomArray[0];
}
public int getMax(int[] randomArray) {
// find the highest number
return randomArray[MAX];
}
}
IntegerArray class:
public class IntegerArray {
public static void main(String[] args) {
// set up the constant for the size of the array
final int MAX = 10;
int sum = 0;
int average = 0;
int[] randomArray = new int[MAX];
for (int index = 0; index < MAX; index++)
// values of the array go from 0-10
randomArray[index] = (int) (Math.random() * 10);
// prints the array
for (int value : randomArray)
System.out.println(value);
System.out.println("The length of the array is: " + randomArray.length);
Driver driver = new Driver();
System.out.println(driver.getAverage());
}
}
Reply to the question in the comments:
You should give the randomArray as the parameter with your getAverage method so that method knows on which array it should operate, example: driver.getAverage(randomArray);
Your getAverage method also has some flaws:
1. Your sum variable should be outside the loop because else you would set your sum to 0 every time you iterate inside the loop.
2. int[] randomArray = null; You shouldn't really do this line at all, this line will create a NEW int array and set its value to null while you should you use the int array you give as a parameter.
So your getAverage method becomes:
public int getAverage(int[] randomArray) {
int sum = 0;
for (int index = 0; index < randomArray.length; index++) {
sum = sum + randomArray[index];
}
int average = sum / randomArray.length;
return average;
}
Currently your main class doesn't reference Driver at all, so your code cannot be called.
System.out.println(randomArray[].getAverage());
On this line randomArray is still just an array of integers (int[] randomArray = ...).
You will need to create an instance of Driver, pass in whatever array you're wanting to use, and then do .getAverage() on that.
randomArray is null and you are trying to read from a null array.
you need to define randomArray as a class member, not a local variable in all functions.
Local variables inside functions cannot be used as soon as function ends, and using the same name in other functions cannot help that.
Also:
define sum and average before loop. calculate and return average after loop.
Among other things your main issue seems to be a fundamental misunderstanding of scope rules. For example:
void method () {
int someVariable;
}
void method2 () {
someVariable = 2; // <-- Error.
}
In that code someVariable is local to method and is not available outside of it. You could not access it in method2.
I suggest you have a read not only of the above scope rules link, but of the official tutorial on member variables as well, which also describes scope. The information there will help you come up with a final strategy.
In your specific case your two most reasonable options are:
You could make randomArray a member field of your class (see above links).
You could pass randomArray as a parameter to your various methods (e.g. as a parameter to getAverage, see also the official tutorial on passing information to a method).
You have a few other issues, some mentioned in the other answers here, but my take is that is your primary confusion here. Read through the official tutorials (the docs.oracle.com links above), they're concise and well-written, and will fill in the blanks of some of your missing concepts. After you do that, give it another shot.
By the way, as for your compiler error on:
System.out.println(randomArray[].getAverage());
Unfortunately randomArray[].getAverage() simply does not make enough sense to justify a full explanation of how the compiler is interpreting it, so suffice it to say: No, that's wrong. :)
You'll want to check out that "passing information to a method" tutorial mentioned above, because it looks like you're trying to express something like this (option 2 above):
int getAverage (int randomArray[]) {
...
}
System.out.println(getAverage(randomArray));
As an aside: Note that the average of a bunch of integers isn't necessarily an integer itself (the average of 1 and 2 is 1.5). You might consider computing and returning a float or a double instead.

How to find the highest and the lowest number stored in an array? [duplicate]

This question already has answers here:
How to find max and min value [duplicate]
(3 answers)
Closed 6 years ago.
I am trying to print the highest and lowest integer number stored in an array. I am able to print the highest but for the lowest I am not getting the correct result.
Consider my two classes below :
class ArrayUtilityNew
{
public static int findMaxMin(int a[])
{
int n=a.length;
int n2=n-1;
int minNo=0;
int count=0;
int maxNo=0;
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
if(a[i]<a[j])count++;
}
//This gives the highest no. if the count is 0
if(count==0)
{
maxNo=a[i];
}
//Lowest no. shall be gained here if the count is greater
// than the no of elements in the array
// if(count>n)
// {
// minNo=a[i];
// }
count=0;
}
return maxNo;
}
}
class ArrayInteractionsNew
{
public static void main(String arr[])
{
int one[]={3,20,1999,2,10,8,999};
int answer=ArrayUtilityNew.findMaxMin(one);
System.out.println("The highest no in the array is "+answer);
}
}
Is the logic behind the second if not correct or is there some other mistake?
How can it be corrected?
You could return an int[] of min and max. Start with an array of two elements, loop over the array1 like
public static int[] findMinMax(int[] a) {
int[] result = { Integer.MAX_VALUE, Integer.MIN_VALUE };
for (int i : a) {
result[0] = Math.min(result[0], i);
result[1] = Math.max(result[1], i);
}
return result;
}
The result will be an array with the first element being the minimum value2. Then to test it,
public static void main(String[] args) {
int[] arr = { 3, 20, 1999, 2, 10, 8, 999 };
int[] minMax = findMinMax(arr);
System.out.printf("%s: min=%d, max=%d%n",
Arrays.toString(arr), minMax[0], minMax[1]);
}
And I get (as I would expect)
[3, 20, 1999, 2, 10, 8, 999]: min=2, max=1999
1Here, with a for-each loop.
2And the second element being the maximum.
I think your solution is way too complex... A better and more efficient solution would be this:
int n=a.length;
int minNo=a[0];
int maxNo=a[0];
for(int i=1;i<n;i++)
{
if(a[i] > maxNo) {
maxNo = a[i];
} else if(a[i] < minNo) {
minNo = a[i];
}
}
// do whatever you want with maxNo and minNo
Also an even more efficient (in the code size way) way would be to use lists or streams because you can do one-liners with it.
EDIT: less ambiguous code and explanations about efficiency
Your answer is n^2. To find min and max it only needs to be order n.
In other words you only need to look linear.
Do a loop that looks through the list once. Keep track of min and max as you go. Initially set min = maxvalue and max=minvalue. When you find a value smaller than min, it becomes the new min.
Here is an example in pseudo code.
min = max_int
max = min_int
for (i=0; i < array.length; i++)
if array[i] < min
min = array[i]
if array[i] > max
max = array[i]
Your approach, if it even works, is needlessly complicated.
Create two variables: minNo and maxNo.
Set minNo = Integer.MAX_VALUE and maxNo = Integer.MIN_VALUE.
Loop through the array. If the element is >= maxNo, assign its value to maxNo. Also (not instead -- i.e., not else if!), if the element is <= minNo, then assign its value to minNo.
After the loop, minNo and maxNo will be correctly assigned.
public static void minMax(int []arr){
int min = arr[0];
int max = arr[0];
for(int i=1; i<arr.length; i++){
min = Math.min(min,arr[i]);
max = Math.max(max,arr[i]);
}
//do whatever you want with the max and min
}
Thanks to the Streaming API in java8, this is a two-liner:
int[] array = new int[] {5,7,2,9,10,24,3,23};
int min = IntStream.of(array).min().getAsInt();
int max = IntStream.of(array).max().getAsInt();
Or as a more efficient 3-liner:
Arrays.parallelSort(array);
int min = array[0];
int max = array[array.length -1];

how can i find the average of this?

I'm new to java programming and i just cant figure out how to find the average of an array nor do i know how to print the array backwards. This is my code so far:
public static void forwards(int nums, int arrayNums[]){
for(int a=0;a<arrayNums.length;a++){
nums =(int)(Math.random()*90+10);
System.out.print(nums+" ");
}
System.out.println();
System.out.println();
//Average of the array
int average=0;
for(int b=0;b<arrayNums.length; b++){
average=(average+arrayNums[b]);
}
System.out.println();
System.out.println(average);
}
public static void backwards(int nums, int[] arrayNums){
//backwards of the array
for(int a=arrayNums.length; a>0;a--){
System.out.print(nums+" ");
}
}
public static void main (String [] args){
int[] arrayNums = new int [Integer.parseInt
(JOptionPane.showInputDialog("How many numbers do you want to input?"))];
int nums = 1;
forwards(nums,arrayNums);
System.out.println();
backwards(nums,arrayNums);
For average ---->
for (int i = 0; i < array.length; i++)
{
sum += array[i];
}
int avegare = sum / array.length;
For Backwards ---->
for(int i = Array.length - 1; i >= 0;i--)
Backwards should start with arrayNums.length-1:
public static void backwards(int nums, int[] arrayNums){
//backwards of the array
for(int a=arrayNums.length-1; a >= 0; a--){
System.out.print(arrayNums[a]+" ");
}
}
The reason is that indices go from 0 to array.length-1. That's basically what happens in a for loop.
For the average, you forgot a division by the number of elements...
"i just cant figure out how to find the average of an array nor do i know how to print the array backwards."
For averages, you should use a different method, instead of trying to it in the forwards method
public static double average(int[] arrayNums) {
double sum = 0;
...
double average = // how do you get the average of something?
return average;
}
I started you off with the basic outline. You basically need to add all the numbers to the sum, by looping through the array, then get the average by diving it by the total of numbers in the array. Then you can print out the average like
double average = average(array);
System.out.println(average)
for backwards, you want to print arrayNums[a] instead of nums. You should also start the loop from arrayNum.length - 1 as there is no index in the array arrayNums.length so you would get an ArerayOutOfBounds exception. Also you want the 0th index, so you want to use >=
for(int a = arrayNums.length - 1; a >= 0 ;a--) {
// print arrayNums[a]
You seem to be doing the same wrong thing for forwards as you are in backwards. You want to print the arrays value for each index a, and not nums
I would also create the random array in a different method
public static int[] randomArray(int num) {
int[] random = new int[nums];
.... may array by looping
return random;
}
Then you the main you could just do
int[] array = randomArray(num);
forwards(array);
backwards(array);
double average = average(array);
System.out.println(average);
As you can see, I pass no nums to the methods. I think you should take tha parameter out of the method signatures. I see no use for them.
Here is a simple way to find the average. Just add up each of the elements, and then divide by the total number of elements in the array:
public static double average(int[] array)
{
int average =0;
for(int i =0; i< array.length; i++ )
{
average += array[i];
}
return average/array.length;
}
Here is a backwards method. Start at array.length-1, which is the last index. From there, iterate down i--, and then end when i is zero.
public static void printBackwards(int[] array)
{
for(int i =array.length-1; i>= 0; i--)
{
System.out.print(array[i] +" ");
}
}
When you call the methods, this is the syntax you should use:
double avg = average(arrayNums);
System.out.println(avg);
printBackwards(arrayNums);

Categories

Resources