[英]java - How to - Running total that is not in main function
I need to keep a running total but it has to be in my calc class, not main. 我需要保持运行总计,但是它必须在我的calc类中,而不是main中。 My program does what I need except for a running total in calc. 我的程序可以执行我需要的工作,但calc可以运行总计。 For the life of me, I can't figure it out. 对于我的一生,我无法弄清楚。 How would I go about setting up a way for keeping a running total that is not in my main function? 我将如何建立一种方法来保持总功能不在我的主要职能范围内?
public class CalculatorImpl implements CalculatorInterface {
private int total = 0;
@Override
public void reset() {
// TODO Auto-generated method stub
total = 0;
}
@Override
public double plus(int a) {
// TODO Auto-generated method stub
total = total + a;
return 0;
}
@Override
public double minus(int a) {
// TODO Auto-generated method stub
total = total - a;
return 0;
}
@Override
public double star(int a) {
// TODO Auto-generated method stub
total = total * a;
return 0;
}
@Override
public double slash(int a) {
// TODO Auto-generated method stub
total = total / a;
return 0;
}
@Override
public double equal() {
// TODO Auto-generated method stub
return total;
}
}
this is main program 这是主程序
import java.util.Random;
public class Main {
public static void main(String[] args) {
Random random = new Random(1000);
CalculatorInterface calc = new CalculatorImpl();
System.out.println("Answer 1: " + calc.equal()); // Print the initial
// value stored in
//calc should return 0
// Test calc class
for (int i = 0; i < 26; i++) {
// Get a random integer to select one of the four methods
int r = random.nextInt(4);
// Test statement for what it is selecting
// System.out.println( "Int: " + r );
switch (r) {
case 0:
calc.plus(random.nextInt(10));
break;
case 1:
calc.minus(random.nextInt(10));
break;
case 2:
calc.slash(random.nextInt(10));
break;
case 3:
calc.star(random.nextInt(10));
break;
default:
}
}
// Should return -218.0
System.out.println("Answer 2: " + calc.equal());
// Reset/clear
calc.reset();
// Should now have 0 in the calc, print 0
System.out.println("Answer 3: " + calc.equal());
// Simple example
calc.plus(2);
calc.minus(1);
calc.star(5);
calc.slash(10);
// Should now have 0.5 in the calc, print 0.5
System.out.println("Answer 4: " + calc.equal());
}
}
here is the other class 这是另一堂课
public interface CalculatorInterface {
public void reset();
public double plus( int a );
public double minus( int a );
public double star( int a );
public double slash( int a );
public double equal();
}
The total is an int
and can therefore not hold the value 0.5
. 总数是一个int
,因此不能保存值0.5
。 Declare it as double
. 将其声明为double
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.