Java Based Code. Please verfiy in JDK. Thankyou <3 1.Write a do-while loop that
ID: 3693136 • Letter: J
Question
Java Based Code. Please verfiy in JDK. Thankyou <3
1.Write a do-while loop that asks the user to select a task from the following menu to continue:
1.Task 1
2.Task 2
3.Task 3
4.Exit
Read the selection from the keyboard then write the switch statement for the following:
For task 1, display the message “Finish Task 1”
For task 2, display the message “Finish Task 2”
For task 3, display the message “Finish Task 3”
For task 4, display the message “Terminate the program”
The do.. while loop ends when users select 4 from the menu
Explanation / Answer
import java.util.Scanner;
/**
* @author
*
*/
public class Task {
/**
* @param args
*/
public static void main(String[] args) {
Scanner scanner = null;
try {
// scanner to read data from console
scanner = new Scanner(System.in);
// declare choice to hold task choice
int choice;
// start do-while
do {
// prompt menu
System.out.println(" 1.Task 1 2.Task 2 3.Task 3 4.Exit");
// prompt choice
System.out.print(" Enter your Choice:");
// read menu choice
choice = scanner.nextInt();
// start switch case
switch (choice) {
case 1:
System.out.println("Finish Task 1");
break;
case 2:
System.out.println("Finish Task 2");
break;
case 3:
System.out.println("Finish Task 3");
break;
case 4:
System.out.println("Terminate the program");
break;
default:
System.out.println("Invalid choice");
break;
}
} while (choice != 4);// terminate do-while when choice is 4
} catch (Exception e) {
// TODO: handle exception
} finally {
scanner.close();
}
}
}
OUTPUT:
1.Task 1
2.Task 2
3.Task 3
4.Exit
Enter your Choice:1
Finish Task 1
1.Task 1
2.Task 2
3.Task 3
4.Exit
Enter your Choice:2
Finish Task 2
1.Task 1
2.Task 2
3.Task 3
4.Exit
Enter your Choice:3
Finish Task 3
1.Task 1
2.Task 2
3.Task 3
4.Exit
Enter your Choice:4
Terminate the program
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.