Java 四规则计算

Java 四规则计算,java,calculation,Java,Calculation,我已经用main方法编程了 不幸的是,它不起作用 它是编程基本计算器 public class Taschenrechner { int zahl1 = 2; int zahl2 = 6; int Ergebnis = 0; public int sub(int zahl1, int zahl2 ){ int Ergebnis = zahl2 - zahl1; return Ergebnis; } public int add(int zahl1, int zahl2){

我已经用main方法编程了

不幸的是,它不起作用

它是编程基本计算器

public class Taschenrechner {
int zahl1 = 2;
int zahl2 = 6;
int Ergebnis = 0;

public int sub(int zahl1, int zahl2 ){
    int Ergebnis = zahl2 - zahl1;
    return Ergebnis;
}
public int add(int zahl1, int zahl2){
    int Ergebnis = zahl2 + zahl1;
    return Ergebnis;
}
public int mult(int zahl1, int zahl2){
    int Ergebnis = zahl2 * zahl1;
    return Ergebnis;
}
public double div(int zahl1, int zahl2){
    double Ergebnis = (double) zahl1/zahl2;
    return Ergebnis;
} 
public static void main(String[] args){
    sub(6,2);
    add(6,2);
    mult(6,2);
    div(6,2);
}
}

Java程序需要一个起点,这是主要的方法。没有main方法,您无法运行任何东西。但是您可以不使用main方法进行编译。您可以编译类和其他构造的负载,将其打包为jar,并将其作为依赖项添加到具有main方法的其他代码中

编辑(因为问题变成了具体的编译错误)

您正试图从静态上下文(从具有关键字
static
/main方法)使用实例方法(不带
static
关键字的类的方法)。为了使用实例方法,需要使用
new
关键字创建类的实例。您的示例如下所示:

public class Taschenrechner {

  // Removed instance variables from here because they were not actually used.
  // You should only use instance variables when you want to store state between your method calls (store the last calculation to undo it for example)

  public int sub(int zahl1, int zahl2 ){
      int Ergebnis = zahl2 - zahl1;
      return Ergebnis;
  }
  public int add(int zahl1, int zahl2){
      int Ergebnis = zahl2 + zahl1;
      return Ergebnis;
  }
  public int mult(int zahl1, int zahl2){
      int Ergebnis = zahl2 * zahl1;
      return Ergebnis;
  }
  public double div(int zahl1, int zahl2){
    double Ergebnis = (double) zahl1/zahl2;
    return Ergebnis;
  } 

  public static void main(String[] args){
    Taschenrechner taschenrechner = new Taschenrechner();
    int subtractionResult = taschenrechner.sub(6,2);
    int addingResult = taschenrechner.add(6,2);
    int multiplicationResult = taschenrechner.mult(6,2);
    int divisionResult = taschenrechner.div(6,2);
    System.out.println("subtractionResult = " + subtractionResult); // prints 4
    System.out.println("addingResult = " + addingResult); // prints 8
    System.out.println("multiplicationResult = " + multiplicationResult); // prints 12
    System.out.println("divisionResult = " + divisionResult); // prints 3
  }
}

还要注意的是,我从代码中删除了实例变量,因为它们被方法作用域变量隐藏,因此未使用。

我更改了代码。还有一个错误“error:non-static method sub(int,int)不能从静态上下文引用”`public static void main(String[]args){sub(6,2);add(6,2);mult(6,2);div(6,2);}`请将主方法代码也添加到问题中,因为错误不是来自该类。但是没有主方法代码的事件,很明显什么地方出了问题,你可以从这个线程中找到答案,但是另一个方法不是静态的。也就是说,它在没有新操作员的情况下工作。还是我学错了?嗨@tonini,欢迎来到SO!请避免问诸如“我的代码不工作”之类的问题。显然有些东西不起作用,否则你为什么要在这里发帖;)请包含调试信息,以便其他人能够理解哪些不起作用。有关更多信息,请参见此处: