Hi.... How do I get the return statement to work in this code? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Hi.... How do I get the return statement to work in this code?

public class ArrayList { public static void main(String[]args) { double[]g={1.9,2.9,3.4,3.5}; double max=g[0]; for (int i=1;i<g.length;i++){ if (g[i]>max)max=g[i]; } return max; } }

27th Feb 2017, 5:24 AM
Ricardo Chitagu
Ricardo Chitagu - avatar
6 Answers
+ 2
public class ArrayList { public static void main(String[] args) { double[] g = {1.9,2.9,3.4,3.5}; double max = getMax(g); System.out.println(max); } private static double getMax(double[] nums) { double max = nums[0]; for (int i = 1; i < nums.length; i++){ if (nums[i] > max) { max = nums[i]; } } return max; } } You are trying to create a method within the main method and return from it, that won't work. Not to mention some formating issues. This should accomplish what you are after.
27th Feb 2017, 5:50 AM
ChaoticDawg
ChaoticDawg - avatar
0
Try to create variable and put max in it and then u'll could work with your new variable ("return max" -> my_var = max). Also you can wrap your loop into function.
27th Feb 2017, 5:36 AM
Tony Loa
Tony  Loa - avatar
0
public static void main(String[]args) { double[]g={1.9,2.9,3.4,3.5}; double var=max ; double max=g[0]; for (int i=1;i<g.length;i++){ if (g[i]>max)max=g[i]; } return max; } } I did its returning an error
27th Feb 2017, 5:45 AM
Ricardo Chitagu
Ricardo Chitagu - avatar
0
can you tell me exactly where I need to adjust
27th Feb 2017, 5:46 AM
Ricardo Chitagu
Ricardo Chitagu - avatar
0
thanks chaotic dawg ...it works
27th Feb 2017, 5:55 AM
Ricardo Chitagu
Ricardo Chitagu - avatar
0
guys how do I get the code to return 1if the maximum number is duplicated else it should return 0??
27th Feb 2017, 8:56 AM
Ricardo Chitagu
Ricardo Chitagu - avatar