Hello, OnlineGDB Q&A section lets you put your programming query to fellow community users. Asking a solution for whole assignment is strictly not allowed. You may ask for help where you are stuck. Try to add as much information as possible so that fellow users can know about your problem statement easily.

I run a file within a project but it keeps giving me the output of the previous file. How do I fix this?

+5 votes
asked Feb 19, 2025 by Alejandra Guillen Garcia (170 points)
I'm super new to programming btw!

So I'm taking a Java Course and it tells me to make project and then I create 4 files and each is different. One prints hello world, the other shows me what errors look like, finding the max of some words, and then the grade of a class. but when I try to find the max of some words or grade of a class it keeps outputting the previous codes answers. Am I doing something wrong?

1 Answer

0 votes
answered Feb 20, 2025 by Peter Minarik (101,340 points)

In your project, you can have as many classes or functions as you want.

However, when you run your project, there can be only one entry point, that is where the execution of the code begins.

Usually, it is called a main function (in languages like C/C++, Java, C#, etc). If all of your classes have a main function, then you need to tell the compiler, which class's main function to use.

Probably an easier option is to have your 4 classes, exercises if you want to call them that and have a 5th class, that is to store the program class with the main function. This main function will then instantiate (call the constructor of) one of your classes (you can edit which one before you run the project).

Below I demonstrate this with one Main and 2 other classes.

Main.java

public class Main
{
    public static void main(String[] args)
    {
        Hello hello = new Hello();
        //Error error = new Error();
        // Other classes commented out here
    }
}

Hello.java

public class Hello
{
    public Hello()
    {
        System.out.println("Hello");
    }
}

Error.java

public class Error
{
    public Error()
    {
        System.out.println("Integral division by zero is not allowed!");
        int error = 2 / 0;
    }
}
commented Jan 5 by Kat (100 points)
How do you navigate between files to edit code or run only one java file in a project?
Welcome to OnlineGDB Q&A, where you can ask questions related to programming and OnlineGDB IDE and receive answers from other members of the community.
...