0
.
├── addition
│   └── Add.java
└─ main.java

This is the current file structure of my program. And these are the contents of main.java. and Add.java respectively.

import java.util.Scanner;

public class main {
    public static void main(String[] args) {
        System.out.print("First number: ");
        var user_input = new Scanner(System.in);
        int x = user_input.nextInt();

        System.out.print("Second number: ");
        int y = user_input.nextInt();

        var result = addition.Add.add(x, y); // <-- error in this line
        var output = x + " + " + y + " = " + result;
        System.out.println(output);
    }
}
public class Add {
    public static int add(int x, int y) {
        return x + y;
    }
}

I am unsure how I'm supposed to import the Add class into main.java. Not sure if it matters but I go to the root of the project and run javac *.*. To compile all the java source files.

1
  • 1
    You should be using packages Apr 23, 2021 at 1:08

1 Answer 1

0

If can use IDE: eclipse, and then import package addition

All code like this:

Add.java:

package addition;

public class Add {
    public static int add(int x, int y) {
        return x + y;
    }
}

main.java

import java.util.Scanner;

import addition.Add;

public class main {
    public static void main(String[] args) {
        System.out.print("First number: ");
        Scanner  user_input = new Scanner(System.in);
        int x = user_input.nextInt();

        System.out.print("Second number: ");
        int y = user_input.nextInt();

        Add add = new Add();
        int result = add.add(x, y); // <-- error in this line
        String output = x + " + " + y + " = " + result;
        System.out.println(output);
    }
}
1
  • 1
    the add method is static Apr 23, 2021 at 2:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.