Unlimited sum Learn programming Java

Lesson:

Dynamic Memory Management


Exercise:

Unlimited sum 94


Objetive:

Create a program to allow the user to enter an unlimited amount of numbers. Also, they can enter the following commands:

"sum", to display the sum of all the numbers entered so far.
"view", to display all the numbers entered.
"end", to quit the program.

This is an execution sample:
Number or command? 5
Number or command? 3
Number or command? view

Entered numbers:
5
3

Number or command? 6
Number or command? sum
Sum = 14
Number or command? -7
Number or command? end


Code:

package Comands;
import java.util.*;
public class Main
{
	static void main(String[] args)
	{
		boolean exit = false;

		String answer;

		ArrayList mylist = new ArrayList();
		int total = 0;
		do
		{
			System.out.print("Number or command? ");
			answer = new Scanner(System.in).nextLine();

			if (answer.toLowerCase().equals("view"))
			{
				System.out.println("Entered numbers: ");
				for (int number : mylist)
				{
					System.out.println(number);
				}
			}
			else if (answer.toLowerCase().equals("sum"))
			{
				System.out.printf("Sum: %1$s" + "\r\n", total);
			}
			else if (answer.toLowerCase().equals("end"))
			{
				exit = true;
			}
			else
			{
				try
				{
					int number = Integer.parseInt(answer);
					mylist.add(number);
					total += number;
				}
				catch (java.lang.Exception e)
				{
					System.out.println("Command is not recognized by the system");
				}
			}
		} while (!exit);

	}
}