好的,所以我一直在研究一个带有类的计算器(要使用类而不是函数),当我运行它时,无论我输入什么或者说要用于运算符,我都会返回零。这是我的代码:
主要课程:
import java.util.Scanner;
//numof = number of numbers in array
// numarrays = the array for user input
// finial = finial number aka the answer
public class Calculator {
public static double finial;
/**
* @return the finial
*/
public static double getFinial() {
return finial;
}
/**
* @param numof the finial to set
*/
public static void setFinial(double finial) {
finial = numof;
}
public static int numof;
/**
* @return the numof
*/
public static int getNumof() {
return numof;
}
/**
* @param numof the numof to set
*/
public static void setNumof(int numof) {
numof = numof;
}
public static double[] numarrays;
/**
* @return the numarrays
*/
public static double[] getNumarrays() {
return numarrays;
}
/**
* @param numarrays the numarrays to set
*/
public static void setNumarrays(double[] numarrays) {
numarrays = numarrays;
}
@SuppressWarnings("resource")
public static void main (String[] args) {
System.out.println("Hello and welcome to my calculator, in this calculator you can add, subtract or multiply");
System.out.println("For the next step I need to know how many numbers you would like to input? ");
int numof;
Scanner numofnums= new Scanner(System.in);
numof = numofnums.nextInt();
Calculator.setNumof(numof);
System.out.println("So next you are going to input the numbers");
double[] numarrays = new double[numof];
for (int k=0; k < numof; k++){
System.out.println("Please enter number");
Scanner input = new Scanner(System.in);
numarrays[k] = input.nextDouble();
}
Calculator.setNumarrays(numarrays);
System.out.println("Please enter what you would like to do with these numbers add,subtract,avg,multiply");
Scanner OP = new Scanner(System.in);
String OPerator= OP.next();
if (OPerator.equals ("add")){
Add.adding();
}
else if (OPerator.equals ("subtract")){
subtract.subtracting();
}
else if (OPerator.equals ("multiply")){
multiply.multiplying();
}
else if (OPerator.equals ("avg")){
avg.avging();
}
System.out.println("The answer is " + Calculator.getFinial());
}
}
这是添加类:
public class Add extends Calculator {
public static void adding() {
double finial = 0;
for (int h = 0; h < Calculator.getNumof(); h++){
finial = finial + Calculator.getNumarrays()[h];
}
Calculator.setFinial(finial);
}
}
我还有三个课程,但只是操作员课程,如果你需要它,请告诉我
答案 0 :(得分:0)
快速浏览一下显示一些重要的基本问题。例如,在基本的设置器中,例如:
public static void setFinial(double finial) {
finial = numof;
}
来自您的代码,您最有可能的是
public static void setFinial(double paramFinial) {
finial = paramFinial;
}
如果静态变量和参数具有相同的名称,则无法同时访问它们。编译器会认为你在谈论参数。另外,请注意你的setter使用参数paramFinial而不是numof
可能无意的引用。
如果您要评论finial
,numof
和其他变量所代表的内容,那么阅读其余代码将会容易得多。