AdamK
AdamK

Reputation: 74

Using results from the loops for another one

I have to say sorry because I know that this is kind of a silly question (I just started learning java) but how can I use a "while" loop result for another loop? I need to prepare a program that will add digits from two given numbers. First of all I need to add digits from number1 then number2 and at the end sum digits of both. sum1 and sum2 are working pretty nice but its ending at this point, sum3, and operations in loop nr3 are invisible for my machine.

I think I should combine it somehow into one loop but I got no idea how (I'm learning from Horstmann and Cadenhead books and there is no good answer)

Thank you for answer and I will be glad if it's not going to be a straight code upgrade but maybe some kind of hint where or what I should search! Thank You :) I have got something like this:

public static void main(String[] args) {
    int sum1 = 0;
    int sum2 = 0;
    int sum3 = 0;
    Scanner scn = new Scanner(System.in);
    System.out.println("1 : ");
    int l1 = scn.nextInt();
    System.out.println("2 : ");
    int l2 = scn.nextInt();
    System.out.println((0 > l1 || 0 > l2 ? "ERROR-NEGATIVE NUMBER" : "OK"));
    while (l1 > 0) {
        sum1 += l1 % 10;
        l1 /= 10;
    }
    //System.out.println(sum1);
    while (l2 > 0) {
        sum2 += l2 % 10;
        l2 /= 10;
    }
    //System.out.println(sum2);
    while (sum1+sum2>0) {
        sum3 +=(sum1+sum2) %10;
        (sum1+sum2) /=10;
    }

}

Upvotes: 0

Views: 70

Answers (2)

saeed foroughi
saeed foroughi

Reputation: 1718

the best way is to use a method for that purpose and reuse it:

public static void main(String[] args) {
    int sum3 = 0;
    Scanner scn = new Scanner(System.in);
    System.out.println("1 : ");
    int l1 = scn.nextInt();
    System.out.println("2 : ");
    int l2 = scn.nextInt();
    System.out.println((0 > l1 || 0 > l2 ? "ERROR-NEGATIVE NUMBER" : "OK"));
    sum3 = addDigit(addDigit(l1)+addDigit(l2))

}

private static int addDigit(int number){
    int sum = 0;
    while (number > 0) {
        sum += number % 10;
        number /= 10;
    }
    return sum;
}

Upvotes: 1

Iłya Bursov
Iłya Bursov

Reputation: 24146

the main problem is that result of /= operator should be stored somewhere, result of sum1+sum2 does not provide such storage.

to make this code work, you need to store sum1+sum2 into some temp variable, so replace

while (sum1+sum2>0) {
    sum3 +=(sum1+sum2) %10;
    (sum1+sum2) /=10;
}

with something like:

int tempsum = sum1 + sum2;
while (tempsum > 0) {
    sum3 += tempsum % 10;
    tempsum /= 10;
}

Upvotes: 0

Related Questions