简体   繁体   中英

Finding max Int using recursion in Java

Hello I'm new to java so please be gentle. I'm sure the code seems long winded and ugly but we all start somewhere.

I'm trying to find the largest Number in an array using recursion. My output is 0 for any array the default -1 is working.

Any help to steer me in the right direction would be a great help

Thank you all in advance-

public int maxInt(MyList<Integer> m){
int result = 0;
int e0;
int len = m.length();
int e1;

if (len == 0) {
    result = -1;
    }
else if(len == 1) {
    e0 = m.getElement(0);
    result = e0;
    }   
else if(len == 2) {
    e0 = m.getElement(0);
    e1 = m.getElement(1);
    if (e0 > e1) {
        result = e0;
    }else {
        result = e1;
        }
    }
else if(len > 2) {
    e0 = m.getElement(0);
    e1 = m.getElement(1);
    if (e0 <= e1){
        m.removeElement(0);
        result = maxInt(m);
        m.addElement(0, e0);
        }       
    }   
return result;
}

In your len > 2 case, if e0 is the larger number, nothing happens. In general that code is just broken - you want to first run the m.removeElement , maxInt , m.addElement code to obtain the largest number from the sublist, and then compare that number vs. element 0, returning whichever one is larger.

I suggest you learn to debug - just writing code and then if it doesn't work praying someone on SO helps out is... tedious coding at best ;)

It's easy! Take a pen and paper and write along with the computer. You run the program, in your head, writing down what's happening. Use a debugger to step through the code (or, if you must, a boatload of System.out.println statements sprinkled throughout your code).

Every time the program has a different result than what you think? You found a bug.

It's that simple.

You say you are new to Java but this really has nothing to do with Java . This has to do with understanding recursion and the traps and pitfalls are the same (or very similar) in other languages as well.

I can tell you right now the code should be no more than 10 lines (and less if you have a sublist method.

I would recommend you try some simple things first to get the feel for recursion. Summing the first n odd integers or simply printing the values of 1 thru n. And then printing the values n thru 1 by only changing the location of the print statement.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM