如何使用Scanner对象的输入创建运行总计

时间:2016-07-30 06:11:12

标签: java

我正在编写一个计算运行总计的程序,直到用户输入999,此时总计(不包括999)应该在屏幕上。

我意识到我可能不得不从总数中扣除999,但我的问题是我无法将其全部吐出来。我认为问题是我的Math类没有正确地从num变量增加numTotal。请帮忙。 提前致谢

public class Program {

public static void main(String[] args) {

    Scanner kb = new Scanner(System.in);
    String input = kb.nextLine();
    Scanner scn = new Scanner(input);
    int num = scn.nextInt();
    Math math1 = new Math(num,0);
    while(num != 999){
        math1.adder(num);
        input = kb.nextLine();
    }

    System.out.println(math1.getNumTotal());
} //main

}

课程结束

public class Math {

private int num;
private int numTotal;

public Math(int num, int numTotal){
    this.num = num;
}



//get//

public int getNum(){
    return this.num;
}

public int getNumTotal(){
    return this.numTotal;
}

//set//

public void setNumTotal(int value){
    this.numTotal = value;
}

public void setNum(int value){
    this.num = value;
}

//other
public void adder(int num){
    numTotal = numTotal + num;
}



}

课程结束

1 个答案:

答案 0 :(得分:0)

我修改了您的代码,如下所示

import java.util.Scanner;

public class Program {
    public static void main(String[] args) {
        Scanner kb = new Scanner(System.in);
        int num = 0;
        Math math1 = new Math(num);
        while (num != 999) {
            num = kb.nextInt();
            if (num != 999) {
                math1.adder(num);
                System.out.println("Total till now:" + math1.getNumTotal());
            }
        }
        System.out.println(math1.getNumTotal());
        System.out.println(math1.getNum());
        kb.close();
    }

}

class Math {
    private int numTotal;
    private int num;

    public Math(int num) {
        this.num = num;
    }

    public int getNum() {
        return this.num;
    }

    public int getNumTotal() {
        return this.numTotal;
    }

    public void setNumTotal(int value) {
        this.numTotal = value;
    }

    public void setNum(int value) {
        this.num = value;
    }

    public void adder(int num) {
        this.num = num;
        numTotal = numTotal + this.num;
    }

}

这是日志

1
Total till now:1
2
Total till now:3
3
Total till now:6
4
Total till now:10
999
10 //math1.getNumTotal()
4 //math1.getNum()