Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fix "error: class found on application class path: Main" in java for visual studio code

this is my first time posting here and would like how to solve this error message. It appears only sometimes and only lets me build on a program called Main.java. I'm a begginer programmer so please bear with me, this is the code im trying to run:

import java.util.Scanner;
import java.text.NumberFormat;


public class Main {
    public static void main(String[] args) {

        Scanner priceScanner = new Scanner(System.in);
        System.out.print("Price: ");
        int price = priceScanner.nextInt();

        Scanner interestScanner = new Scanner(System.in);
        System.out.print("Interest rate: ");
        double interest = interestScanner.nextDouble();

        Scanner numberOfPaymentsScanner = new Scanner(System.in);
        System.out.print("Number of payments: ");
        int numberOfPayments = numberOfPaymentsScanner.nextInt();

        Double monthlyInterest = interest / 1200;

        Double result = ((double)price * ((interest * Math.pow((1 + 
interest), (double)numberOfPayments))/((Math.pow((1 + interest), 
(double)numberOfPayments)) - 1)));

        NumberFormat currency = NumberFormat.getCurrencyInstance();
        String mortgage = currency.format(result);

        System.out.println("Your mortgage is: " + mortgage);
    }
}

I haven't seen any comprehensible ways to solve this problem online, and the only thing i think could solve it is to reinstall java in another drive and change the classpath.

Thanks for your attention.

like image 672
Pedro Montesinos Navarro Avatar asked Aug 05 '19 13:08

Pedro Montesinos Navarro


2 Answers

I solved it - my mistake. While executing the program using the terminal I was typing java Main.java, whereas the correct execution method was to type java Main.

like image 155
Pedro Montesinos Navarro Avatar answered Sep 20 '22 20:09

Pedro Montesinos Navarro


With Single-file source-code programs which is a new way of executing 1 File Java programs is only available since Java 11. You can run the command: java (Java File Name without .java extension)

java Main.java

Though please take into consideration that this way of executing only works if your Java project is only 1 Java File.

FYI: This single-file source code will be executed fully in memory and you can only import code that came with the JDK you are working. Finally if you want your code to run as fast as possible compile with javac before executing you program.

javac Main.java

java Main

Just be careful that there is no Main.class already in the folder, this may cause a confusion to the compiler.

like image 32
George Avatar answered Sep 21 '22 20:09

George