The following code will always write 0
. Why is that and how do I fix it?
public static void main(String[] args)
{
int[] Array= {5,4,6,3,7,2,8,1,9,0};
int max=0;
System.out.println(maximum(Array,Array.length-1,max));
}
public static int maximum(int[] Array,int length,int max)
{
if (length!=0)
{
if(max<Array[length])
{
max=Array[length];
}
maximum(Array,length-1,max);
}
return max;
}
EJoshuaS - Stand with Ukraine
12.2k63 gold badges59 silver badges86 bronze badges
asked Apr 13, 2017 at 16:51
-
What result are you getting?Andreas Løve Selvik– Andreas Løve Selvik2017年04月13日 16:57:46 +00:00Commented Apr 13, 2017 at 16:57
-
Please elaborate on what you mean by "not working".EJoshuaS - Stand with Ukraine– EJoshuaS - Stand with Ukraine2017年04月13日 16:59:56 +00:00Commented Apr 13, 2017 at 16:59
-
1means it always get 0 in returnShahiryar Arif– Shahiryar Arif2017年04月13日 17:08:46 +00:00Commented Apr 13, 2017 at 17:08
-
@ShahiryarArif I edited to reflect that, hope that's OK.EJoshuaS - Stand with Ukraine– EJoshuaS - Stand with Ukraine2017年04月13日 17:13:19 +00:00Commented Apr 13, 2017 at 17:13
1 Answer 1
When you call maximum
recursively, you don't write returned value.
if (length!=0)
{
if(max<Array[length])
{
max=Array[length];
}
max = maximum(Array,length-1,max); //rewrite max variable
}
return max;
EDIT
And need to initialize first max
value to Array[0]
int max=Array[0];
System.out.println(maximum(Array,Array.length-1,max));
answered Apr 13, 2017 at 16:59
2 Comments
EJoshuaS - Stand with Ukraine
@ShahiryarArif Also, it should be
length != -1
- right now, if the maximum is the first item in the array, it'll only give the second-highest number.Vladimir Parfenov
@ShahiryarArif - I changed my answer
lang-java