import java.util.*;
import java.math.*;
public class Arithmectic {
double mealCost;
int tipPercent;
int taxPercent;
public Arithmectic(double inMeal, int inTip, int inTax){
Scanner scan = new Scanner(System.in);
inMeal = scan.nextDouble();
mealCost = inMeal;
inTip = scan.nextInt();
tipPercent = inTip;
inTax = scan.nextInt();
taxPercent = inTax;
}
public void printValues(){
System.out.println(mealCost);
System.out.println(tipPercent);
System.out.println(taxPercent);
}
public static void main(String[] args) {
Arithmectic rest = new Arithmectic(mealCost, tipPercent, taxPercent);
}
}
**我遇到了
的问题Arithmectic rest = new Arithmectic(mealCost, tipPercent, taxPercent);
有人可以帮助我并解释我为什么会遇到这个错误?**
答案 0 :(得分:0)
如果您的main
属于同一个类(即Arithmectic
),那么您正试图访问该类的实例变量,以便将它们传递给该类的构造函数。
没有任何意义,也无法做到(你无法从静态上下文中访问实例变量)。
如果构造函数正在从用户输入初始化成员,则不需要从外部获取这些参数。
也就是说,在main
中获取用户输入并将其传递给构造函数会更有意义:
public Arithmectic(double inMeal, int inTip, int inTax){
mealCost = inMeal;
tipPercent = inTip;
taxPercent = inTax;
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
double inMeal = scan.nextDouble();
int inTip = scan.nextInt();
int inTax = scan.nextInt();
Arithmectic rest = new Arithmectic(inMeal, inTip, inTax);
}