do-while Menu
Completed
Simulate a menu: read commands until 0. Command 1 X adds X to a total, 2 prints the total. Use a do-while loop. Print bye at the end.
Input
Commands, the last one is 0.
Output
Totals when requested, then bye.
Example
Input
1 5 1 7 2 1 -2 2 0
Output
12 10 bye
Editor
Java
Hints
A do-while loop always runs its body at least once.
Solution explanation
Menus are the classic use of do-while: show/read first, then decide whether to repeat.
Show solution
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int total = 0;
int choice;
do {
choice = sc.nextInt();
if (choice == 1) {
total += sc.nextInt();
} else if (choice == 2) {
System.out.println(total);
}
} while (choice != 0);
System.out.println("bye");
}
}