简体   繁体   中英

How do I tackle a StackOverflowError when I use this. keyword

I have base class Triangle with 3 derived classes Perimetert , Areat and heightt with main method named main1 , main2 and main3 respectively. I am asking the user what operation to perform in the base class. If the user enters 1 the inherited class Perimetert should be invoked, 2 then Areat and so on.

import java.util.*;
public class Triangle
{
public void main1()
{
    this.main1();
}
public void main2()
{
    this.main2();
}
public void main3()
{
    this.main3();
}
public static void main(String args[])
{
    int M , a , b , c , z , y , A , B , C;
    Scanner in = new Scanner(System.in);
    System.out.println("Press 1 to find the perimeter\nPress 2 to find the area\nPress 3 to find the missing height");
    M = in.nextInt();
    Triangle ob = new Triangle();
    switch(M)
    {
        case 1:
        ob.main1();
        break;
        case 2:
        ob.main2();
        break;
        case 3:
        ob.main3();
        break;
        default:
        System.out.println("Sorry, I can only do 3 operations.\nThank You!!!!!");
       }
    }
}

Can someone please correct this code.

The problem with code like this:

public void main1()
{
    this.main1();
}

is that it creates endless loops.

public void main1() // line 1
{
    this.main1(); // line 2
}

line 1 is called (by an external method), it triggers line 2, which calls line 1, which triggers line 2, which calls line 1, ...

So, yes, this is bound to lead to problems. If you want to use recursive methods (methods calling themselves), make sure there is always the possibility for them to end

int counter = 0;
public void main1()
{
    counter += 1;
    if ( counter < 5 )
        this.main1();
}

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