Running totals of variables in a loop.

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • krzemienski
    New Member
    • Mar 2010
    • 2

    Running totals of variables in a loop.

    Hey I am having trouble with loops the problem is as follows;
    My program so far gets me to what I need which is the remainders which are the last digits of the 5 digit number inputted, I need a way for java to keep a running sum of all the remainders and then I need a new variable which is the sum of the remainders after going through the loop.
    Any help is greatly appreciated.

    mport java.util.Scann er;

    public class Document1
    {
    public static void main(String[] args)
    {

    Scanner keyboard = new Scanner(System. in);

    // Obtain initial data from user
    System.out.prin t("Enter 5 digit Integer: ");
    int n = keyboard.nextIn t();
    getRemainder(n) ;
    System.out.prin tln();
    }

    public static void getRemainder(in t n)
    {


    for (int i = 1; i < 6; i++)
    {
    int remainders = n % 10;
    n = n / 10;

    System.out.prin tln(remainders) ;
    System.out.prin tln(n);
    System.out.prin tln(" ");



    }
    int a = n;


    System.out.prin tln(a);
  • jkmyoung
    Recognized Expert Top Contributor
    • Mar 2006
    • 2057

    #2
    Please use [ code ] tags [ / code ] when posting .
    When you say sum, do you mean string wise, or additive wise (sum of digits?)

    Declare a at the top of your function, and set a += n inside your loop.

    Comment

    • krzemienski
      New Member
      • Mar 2010
      • 2

      #3
      Ok, thank you I figured it out,
      int total = 0
      needs to be befor the loop and I needed to use the total inside the loop to keep a running total adding n to it each time.

      Comment

      Working...