I compile and then run this bit of code in java.ex

2019-08-13 01:03发布

I can't seem to figure out what is wrong with this code. Eclipse tells me main method isn't declared. and when I run it in java.exe it tells me "could not find or load main class discount.java" I've spent the last half hour looking for a solution but can't seem to figure it out.

import java.util.Scanner;

    public class Discount
    {
      public static void main (String[] args) 
      {
        Scanner scan = new Scanner( System.in );
        int price;

        System.out.println("Enter the Price:");
        price = scan.nextInt();


        System.out.println( price / 4 * 3  );
      }
    }

The commands I'm using and error I'm getting:

> CD C:\Programing\Misc
> set path=%path%;C:\Program Files\Java\jdk1.8.0\bin
> javac discount.java
> java discount.java
Error: Could not find out or load main class java.discount 

3条回答
太酷不给撩
2楼-- · 2019-08-13 01:14

The filename has to match the classname exactly, so put this in the file Discount.java (discount.java won't work).

Then, from my command-line:

% javac Discount.java
% java Discount 
Enter the Price:
^C
查看更多
Rolldiameter
3楼-- · 2019-08-13 01:26

Have a look at this file hierarchy and how to compile java on command line

enter image description here

查看更多
狗以群分
4楼-- · 2019-08-13 01:30

Are you using java discount.java? That's likely the issue.

Try these two lines: javac discount.java java discount

That should run your main method (assuming that you've correctly named the file discount.java).

--

EDIT: After seeing your comment about changing the class name, you'll want to rename the file to Discount.java. Then run javac Discount.java and java Discount

查看更多
登录 后发表回答