簡體   English   中英

Java代碼這有什么問題?

[英]Java code what is wrong with this?

我真的是編程新手,在netbeans上,我刪除了所有其他文本,以下是我所有的內容,為什么程序無法運行?

我得到的錯誤是,找不到主類。

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package findcost2;
 public class Main 

 /* a program to calculate and display the cost of a product after 
  * sales tax has been added*/

public class FindCost2
        Public static void main (String[] args)
{
      double price,tax;
      price = 500;
      tax = 17.5;
      price = price * (1 + tax/100);// calculate cost
      // display results
      System.out.println("***Product Price Check");
      System.out.println("Cost after tax = " + price);
    }
}

完全嘗試一下,並命名您的Java文件FindCost2.java

package findcost2;

public class FindCost2{

public static void main (String[] args)
{
  double price,tax;
  price = 500;
  tax = 17.5;
  price = price * (1 + tax/100);// calculate cost
  // display results
  System.out.println("***Product Price Check");
  System.out.println("Cost after tax = " + price);
}

}

class Main之后,您缺少大括號,並且在同一源文件中有兩個公共類。 刪除public class Main並將Public更改為public

您可能還應該使用小數來處理貨幣

遲早,每個試圖用Java計算貨幣的人都會發現計算機無法添加。

為什么Public資本? 應該是:

public class FindCost2 {
    public static void main(String[] args) { ... }
}

此代碼存在許多問題:

  1. 外部類( Main )沒有左括號。 插入{括號。

  2. 內部類( FindCost2 )沒有括號。 插入{括號。

  3. 主方法的public修飾符大寫。 以小寫p開頭。

  4. main方法嵌套在一個內部類中。 這真的是不好的形式。 為了使其正常工作,內部類必須是靜態的。 插入static關鍵字。

當這樣放置時,它會編譯:

public class Main {

/*
 * a program to calculate and display the cost of a product after sales tax
 * has been added
 */

public static class FindCost2 {
    public static void main(String[] args) {
        double price, tax;
        price = 500;
        tax = 17.5;
        price = price * (1 + tax / 100);// calculate cost
        // display results
        System.out.println("***Product Price Check");
        System.out.println("Cost after tax = " + price);
    }
}
}

但是,絕對沒有指向外部類( Main )的指向。 只需刪除它。 移除外部類后,內部類( FindCost2 )不再需要是靜態的。 刪除關鍵字。

在一行上聲明多個變量真的很糟糕(例如,雙倍價格,稅金)。 將其分為兩行:

double price;
double tax;

有充分的理由不對貨幣值使用double類型。 通過一些額外的工作,您可以輕松編寫一個簡單的Money類。 javapractices.com上查看有關此內容的完整概述。

希望有幫助!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM