TAGS :Viewed: 9 - Published at: a few seconds ago

[ How do I create a running total using input from Scanner object ]

I am writing a program which is supposed to calculate a running total, until the user inputs 999, at which point the total(not including 999) is supposed to the screen.

I realise I'll probably have to deduct 999 from the total, but my issue is I cannot get it to spit out a total. I think the issue is that my Math class doesn't correctly increment the numTotal from the num variable. Please help. Thanks in advance

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

}

end of class

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;
}



}

end of class

Answer 1


I've modified your code as below

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;
    }

}

And here's the log

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()