-2

I'm working on a program that established methods for mean, med, mode, q1, q3, max and min. the last method should return a 5 number summary(min, q1, med, q3, max) as an array. Since I already have methods established and working properly for all of these I need a simple way to incorporate all these values into a new method and return as an array. I tried this

public static int calcNumsum(int[] a) { 
  int min; 
  int max; 
  int q1; 
  int q3; 
  int med;
  int[] vals = new int[5];
  vals[1] = min; 
  vals [2] = q1; 
  vals [3] = med; 
  vals [4] = q3; 
  vals [5] = max; 
  return vals;

it gave me back a compiling error int[] cannot be converted to int. any suggestions on how to fix this or a better way to return the array?

Cori Sparks
  • 43
  • 1
  • 7

3 Answers3

1

int[][][][][] is a 5 dimensional array, not a one dimensional array with 5 elements.

int[] vals = new int[5];  // this has 5 elements
// ... assign values like vals[0] = whoever etc
return vals;

Or, shorthand

return new int[]{ val1, val2, val3, val4, val5 };

edit: From comments

public static int calcNumsum(int[] a) {
    int min; int max; int q1; int q3; int med; int[] vals = new int[5];
    vals[1] = min; vals [2] = q1; vals [3] = med; vals [4] = q3; vals [5] = max;
    return vals;
}
  • Declared method type is int, but you are returning an int[]
  • All of the int variables you delcared are uninitialized, so your returned array will always be {0,0,0,0,0} as it is now
  • vals[5] is out of range of your array, array indexing starts at 0
  • Taking the parameter a but not using it at all?

Judging by your initial post, you want to take all 5 values and return the array of them all? If that is the case, you can use the cheapo variable number of arguments trick.

public static int[] toArray(int... vals) {
    return vals;
}

and call it like

int[] theVals = toArray(min, q1, med, q3, max);
// theVals[0] = min, theVals[1] = q1, etc
twentylemon
  • 1,218
  • 9
  • 11
0

You are declaring your array incorrectly.

int[] numSum = new int[]{min,q1,med,q3,max};

Try reading this post to understand declaring arrays better: How do I declare and initialize an array in Java?

Community
  • 1
  • 1
Aaron Troeger
  • 165
  • 1
  • 3
  • 17
0
  1. What is the input?

  2. Do you need to return 5 arrays or just 5 values?

Assuming that these answers are obvious and you need 5-dimensional array and not 5 values and nested list-of-lists are not an option, this is not possible directly in java. Java stores n-dimensional array as an one-dimensional array and you can use that. So, effectively, you can create an one dimensional array along with column size and manipulate the values as you want.


As per the changed question, you are returning int[] for a method which is defined to return int.

Change

public static int calcNumsum(int[] a) 

to

public static int[] calcNumsum(int[] a) 
instanceOfObject
  • 2,826
  • 2
  • 44
  • 83