0

Ok this is making my brain melt!! the code compiles just fine but it refuses to display the correct answers in the displayAllResults method. Im not sure how to fix this at all. Ive tried making the methods private as well as having them return values instead of being void. as an example, the method sum gets the sum of the elements in array but will not display them. Im getting 0.

//Main
public class Lab_4_Practice {

  public static void main(String[] args) {

    //Declaring and initializing variables
    int[] randomArray = new int[10];
    int maxIndex = 0;
    int minIndex = 0;
    int total = 0;
    double average = (total / randomArray.length);  

    //Call Methods
    random(randomArray);
    displayRandom(randomArray);
    largest(maxIndex, randomArray);
    smallest(minIndex, randomArray);
    sum(total, randomArray);
    average(total, randomArray);
    sortArray(randomArray);
    displaySorted(randomArray); 
    displayAllResults(randomArray, maxIndex, minIndex, total, average);      
  }
  //***************************************************
  //Method assigns random values to elements
  public static void random(int[] randomArray) {

    for (int i = 0; i <randomArray.length; i++) {
      randomArray[i] = (int)(Math.random() * 300); 
    } 
  }

  //Method prints random values 
  public static void displayRandom(int[] randomArray) {

    System.out.println("Here are 10 random numbers");
    for (int i = 0; i < randomArray.length; i++) {

      System.out.println(randomArray[i]);
    }
      System.out.println("*************************");
  }

  //Method identifies largest index and its element in array
  public static void largest(int maxIndex, int[] randomArray) {

      for (int l = 1; l < randomArray.length; l++) {
        if (randomArray[l] > randomArray[maxIndex]) {
          maxIndex = l;
        }  
      }  
  }

  //Method identifies smallest index and its element in array
  public static void smallest(int minIndex, int[] randomArray) {


      for (int i = 1; i < randomArray.length; i++) {
        if (randomArray[i] < randomArray[minIndex]) {
          minIndex = i;
        }
      }   
  }

   //Method calculates sum of elements
  public static int sum(int total, int[] randomArray) {


    for (int i = 0; i <randomArray.length; i++) {
      total = total + randomArray[i]; 
    } 
    return total;
  } 

  //Method calculates average of elements
  public static void average(int total, int[] randomArray) {


    for (int i = 0; i < randomArray.length; i++) {
      i += randomArray[i];

    }
  }

  //Method sorts array in ascending order
  public static void sortArray(int[] randomArray) {

    for (int i = 0; i < randomArray.length - 1; i++) {
      int currentMin = randomArray[i];
      int currentMinIndex = i;

      for (int j = i + 1; j < randomArray.length; j++) {
        if (currentMin > randomArray[j]) {
          currentMin = randomArray[j];
          currentMinIndex = j;
        }
      }

      if (currentMinIndex != i) {
        randomArray[currentMinIndex] = randomArray[i];
        randomArray[i] = currentMin;
      }
    } 
  }

  //Method prints array in ascending order  
  public static void displaySorted(int[] randomArray) {

    System.out.println("These are the same numbers sorted in ascending order");
    for (int i = 0; i < randomArray.length; i++) {
      System.out.println(randomArray[i] + " ");
    }
      System.out.println("*************************");
  }

  //Method prints results of largest smallest sum and average
  public static void displayAllResults(int[] randomArray, int maxIndex, int minIndex, int total, double average) {

    System.out.println("The largest index is " + maxIndex + " and its value is " + randomArray[maxIndex]);
    System.out.println("The smallest index is " + minIndex + " and its value is " + randomArray[minIndex]);
    System.out.println("The sum of the elements is " + total);
    System.out.println("The average of the elements is " + average);

  }
}
Vince
  • 1
  • 1
  • 1
  • Refer http://stackoverflow.com/help/how-to-ask and http://stackoverflow.com/help/mcve – Balwinder Singh Nov 02 '15 at 04:56
  • Possible duplicate of [Void methods cannot return a value](http://stackoverflow.com/questions/20490874/void-methods-cannot-return-a-value) – laune Nov 02 '15 at 04:59
  • A parameter `int minIndex` isn't capable of returning a value - it is a one way ticket into the method. - Use int methods with *return* to return a value, and make sure to store the returned value - you don't do this with `sum`. – laune Nov 02 '15 at 05:00

4 Answers4

0

Its always recommended that you do all your calculations/manipulations in a different class rather than in the main class itself. Create a different class and inside that code something like this -

public class Example{
public void assign(int[] Array){
    for(int i=0;i<Array.length;i++){
        Array[i]=(int)(Math.random()*300);
    }
}

public void display(int[] Array){
    System.out.println("The 10 elements of the array are:");
    for(int i=0;i<Array.length;i++){
        System.out.println(Array[i]);
    }
}

public int sum(int[] Array) {
    int total =0;
    for(int i=0;i<Array.length;i++){
        total=total+Array[i];
    }
    return total;
}
//write all other methods here in this class.
}

now in the main class inside the main method just declare the array and pass the array to the different functions as per your requirement, something like this -

public static void main(String[] args) {
    int[] randomArray=new int[10];
    Example e=new Example();
    e.assign(randomArray);//this must be called first to assign the values inside the array.
    e.display(randomArray);//call this method if you wish to display the values.
    System.out.println("The sum of the elements are: "+e.sum(randomArray));
}
Aritro Sen
  • 357
  • 7
  • 14
  • "Its always recommended"... needs citation! – Ken Geis Nov 02 '15 at 06:00
  • I am saying that its better to create a different class and define all your methods inside it. – Aritro Sen Nov 02 '15 at 06:02
  • I understand what you are saying. I'm saying that your opinion on the structure of code may be common but it is certainly not universal. – Ken Geis Nov 02 '15 at 06:26
  • 1
    Even more OO would be to make the array a field of the class, rather than use plenty of proper methods that do not access a field. Most code checkers will throw warnings at you, so your idea of how a class should be used aren't mainstream. – laune Nov 02 '15 at 08:31
  • Yes i do agree with you @laune. Its just my way of structuring the code. – Aritro Sen Nov 02 '15 at 08:35
0

I have done little bit changes in your code. You can compare it with your old code. Most of the places you were facing problem because of local variable. Whatever you were supplying to corresponding method and after operation changes made on local variable is not affecting your instance variables. And for largest() and small() method(), you were calling it without sorting your array, because of that it was giving wrong output.

public class StackProblem { public static void main(String[] args) {

    // Declaring and initializing variables
    int[] randomArray = new int[10];
    int maxIndex = 0;
    int minIndex = 0;
    int total = 0;
    double average = 0;

    // Call Methods
    random(randomArray);
    displayRandom(randomArray);
    sortArray(randomArray);

    maxIndex=largest(randomArray);
    minIndex=smallest(randomArray);

    total=sum(randomArray);
    average=average(total, randomArray);

    displaySorted(randomArray);
    displayAllResults(randomArray, maxIndex, minIndex, total, average);
}

// ***************************************************
// Method assigns random values to elements
public static void random(int[] randomArray) {

    for (int i = 0; i < randomArray.length; i++) {
        randomArray[i] = (int) (Math.random() * 300);
    }
}

// Method prints random values
public static void displayRandom(int[] randomArray) {

    System.out.println("Here are 10 random numbers");
    for (int i = 0; i < randomArray.length; i++) {

        System.out.println(randomArray[i]);
    }
    System.out.println("*************************");
}

// Method identifies largest index and its element in array
public static int largest(int[] randomArray) {
    int maxIndex=0;
    for (int l = 0; l < randomArray.length; l++) {
        if (randomArray[l] > randomArray[maxIndex]) {
            maxIndex = l;
        }
    }
    return maxIndex;
}

// Method identifies smallest index and its element in array
public static int smallest(int[] randomArray) {
    int minIndex=0;
    for (int i = 0; i < randomArray.length; i++) {
        if (randomArray[i] < randomArray[minIndex]) {
            minIndex = i;
        }
    }
    return minIndex;
}

// Method calculates sum of elements
public static int sum(int[] randomArray) {
    int localTotal=0;
    for (int i = 0; i < randomArray.length; i++) {
        localTotal+=randomArray[i];
    }
    return localTotal;
}

// Method calculates average of elements
public static int average(int total, int[] randomArray) {

    return total/randomArray.length;
}

// Method sorts array in ascending order
public static void sortArray(int[] randomArray) {

    for (int i = 0; i < randomArray.length - 1; i++) {
        int currentMin = randomArray[i];
        int currentMinIndex = i;

        for (int j = i + 1; j < randomArray.length; j++) {
            if (currentMin > randomArray[j]) {
                currentMin = randomArray[j];
                currentMinIndex = j;
            }
        }

        if (currentMinIndex != i) {
            randomArray[currentMinIndex] = randomArray[i];
            randomArray[i] = currentMin;
        }
    }
}

// Method prints array in ascending order
public static void displaySorted(int[] randomArray) {

    System.out.println("These are the same numbers sorted in ascending order");
    for (int i = 0; i < randomArray.length; i++) {
        System.out.println(randomArray[i] + " ");
    }
    System.out.println("*************************");
}

// Method prints results of largest smallest sum and average
public static void displayAllResults(int[] randomArray, int maxIndex, int minIndex, int total, double average) {

    System.out.println("The largest index is " + maxIndex + " and its value is " + randomArray[maxIndex]);
    System.out.println("The smallest index is " + minIndex + " and its value is " + randomArray[minIndex]);
    System.out.println("The sum of the elements is " + total);
    System.out.println("The average of the elements is " + average);

}
0

[Nobody supports my motion to put this on hold due to [duplicate] - so I feel compelled to write an answer here.]

This is the typical pattern for a method calculating some value from the elements of an array:

public static int largest(int[] array) {
    int maxIndex = 0;
    for (int l = 1; l < array.length; l++) {
        if (array[l] > array[maxIndex]) {
            maxIndex = l;
        }  
    }
    return maxIndex;
}

And you call it like this:

int maxIndex = largest( randomArray );

Parameters with a type of int, long, double, char, short, float, boolean are copied "by value", i.e., the corresponding expression in the call - the actual parameter - is evaluated and the result is stored in a variable with the name of the parameter. This variable is short-lived: when you return from the method call, it is gone. The only way to hand back the value is by using the return mechanism in a non-void method.

If you have an array however, things are a little different. An array is an object, and objects are handled via references, values that tell the computer where the object can be found. This reference is also copied from the point of invocation and stored in a short-lived variable, but you still can access the object it references so that changes of an array (or any object) are possible via code in a method with an object reference as a parameter.

Finally, the code for calculating the average is very much in error.

public static double average( int[] array ) {
    return (double)sum( array )/array.length;
}

and you need a variable of type double to hold the result. (There is a chance that an array might have the length 0, so I'm a little careless there. Do you see why?)

laune
  • 31,114
  • 3
  • 29
  • 42
-1

The variables you are passing to each method are all zero. You need to change those within the main method, since variables in methods are only used and modified within their respective methods, even if they were passed to that method from the main method. It looks like this is what you want:

randomArray = random(randomArray);
displayRandom(randomArray);
maxIndex = largest(maxIndex, randomArray);
minIndex = smallest(minIndex, randomArray);
total = sum(total, randomArray);
average(total, randomArray); //not sure what you're trying to do here; this method does not calculate the average
average = total/randomArray.length; //you probably just want to use this instead of the average() method
randomArray = sortArray(randomArray);
displaySorted(randomArray); 
displayAllResults(randomArray, maxIndex, minIndex, total, average);

Additionally, for each method that is supposed to return a value, you will need to change the return type in the method header from void to the appropriate variable type, as well as add a return statement at the end of each method.

Bethany Louise
  • 646
  • 7
  • 13
  • Don't confuse OP. There's no need to return an array since it is an object. It is not necessary to pass an int variable to a method just for calculating a result which is then returned - why burden the caller with this? – laune Nov 02 '15 at 07:06