Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"The method is not defined for the type" error in simple program in java

Tags:

java

So I'm just trying to learn Java and after watching some tutorials and reading some basic stuff I am stuck about why this won't run:

package Test;

public class TestProg {
    public static void main(String[] args) {
        Fetch fetc = new Fetch();
        fetc.more(10, 20);
    }
}

This is the Fetch class code:

package Test;

public class Fetch {

    public Fetch() {

        System.out.println("Fetched!"); 

        int a = 1;
        int b = 2;
        int c;

        while (a < 100 && b < 200) {
            a++;
            b++;
            c = a + b;
            System.out.println(c);
        }

        public void more(int d, int e) {
            System.out.println(d + e);
        }
    }
}

I am getting a "The method more(int, int) is not defined for the type Fetch" error in TestProg. If I remove the code about the "more" method (in both Classes), the rest of the code runs normally. I am stumped as to why this would happen because the code is extremely similar to the example I'm studying.

like image 682
Antonis427 Avatar asked Jan 28 '26 02:01

Antonis427


2 Answers

Your method more(int d, int e) is within the Fetch() constructor

Your fetch method should be as follows (note the marked } closing the constructor):

package Test;

public class Fetch {



    public Fetch() {

        System.out.println("Fetched!"); 

        int a = 1;
        int b = 2;
        int c;

        while (a < 100 && b < 200) {

            a++;
            b++;
            c = a + b;
            System.out.println(c);
        }
    }//<---- NOTE: closing constructor


    public void more(int d, int e) {

        System.out.println(d + e);


    }

}
like image 154
Richard Tingle Avatar answered Jan 29 '26 15:01

Richard Tingle


more should be located outside the constructor.

That's why indentation is extremely important.. Together we'll make the planet a better place to live in - Indent your code :)

like image 20
Maroun Avatar answered Jan 29 '26 16:01

Maroun



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!