Object-Oriented Programming with Java, part I – Exercise 26

This program adds numbers together until 0 is entered and then shows the sum of the numbers.

My Code

import java.util.Scanner;


public class SumOfManyNumbers {

    public static void main(String[] args) {
        Scanner reader = new Scanner(System.in);
        int sum = 0;
        
        while (true) {
            int read = Integer.parseInt(reader.nextLine());
            if (read == 0) {
                break;
            }

            // do something here
            sum = sum + read;

            System.out.println("Sum now: " + sum);
        }
        
        System.out.println("Sum in the end: " + sum);
    }
}

Model Code

import java.util.Scanner;

 

 

public class SumOfManyNumbers {

 

    public static void main(String[] args) {

        Scanner reader = new Scanner(System.in);

        int sum = 0;

        

        while (true) {

            int read = Integer.parseInt(reader.nextLine());

            if (read == 0) {

                break;

            }

 

            // do something here

            sum += read;

 

            System.out.println("Sum now: " + sum);

        }

        

        System.out.println("Sum in the end: " + sum);

    }

}

Comment

The major difference is that the model answer is “sum += read;” but mine was “sum = sum + read;“. Same thing, different syntax.

Leave a Reply

Your email address will not be published. Required fields are marked *