0

I'm trying to run this code that returns the maximum value in the given array. I'm brand new to Java so I would greatly appreciate any debugging tips.

public class maxVal { public static int max(int[] m) { int maxSoFar=m[0],i; for (i=1; i<m.length;i++) { if (m[i]>maxSoFar) maxSoFar=m[i]; } return maxSoFar; } public static void main(String[] args) { int[] numbers = new int[]{9, 2, 15, 2, 22, 10, 6}; max(numbers); } 

}

4
  • The max method returns a value so you may want to print it out. Commented Jan 7, 2022 at 6:41
  • you are actually running it, you are just ignoring the returned value Commented Jan 7, 2022 at 6:49
  • so I should print out the maxSoFar value rather than returning it? or both? Commented Jan 7, 2022 at 6:51
  • no, you should print the value you just returned Commented Jan 7, 2022 at 6:51

1 Answer 1

1

I think you need to see the answer in the console?

When you run max method it will return the maximum value in the given array. so to see it in the console you have to print it using System.out.println(). or you can also assign it to another variable to use it in somewhere else.

Your code is actually working but you ignore the return value by max method.

here is your code with System.out.println() to print the maximum value

public class maxVal { public static int max(int[] m) { int maxSoFar=m[0],I; for (i=1; i<m.length;i++) { if (m[i]>maxSoFar) maxSoFar=m[I]; } return maxSoFar; } public static void main(String[] args) { int[] numbers = new int[]{9, 2, 15, 2, 22, 10, 6}; int maxVal = max(numbers); System.out.println(maxVal); } } 
Sign up to request clarification or add additional context in comments.

2 Comments

I didn't change the code. :). just add the sout
my bad, still waking up, I missed the main signature for the other method's :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.