In: Computer Science
Write a method in JAVA that does this:
Presents the user with a header stating this is for assignment: Lab, and the names Bob and Bill
Present the user with a menu to run a random method(just make this a dummy method) , another random method method,(just make this a dummy method) or another dummy method (just make this a dummy method)
Repeat the menu until the user enters -1.
Below is your code:
import java.util.Scanner;
public class Assignment {
public static void main(String[] args) {
// printing header
System.out.println("This is for assignment: Lab, Names: Bob and Bill");
// intializing Scanner to take user input
Scanner sc = new Scanner(System.in);
// Initializing variable to get user choice
int choice = 0;
// loop to run till user selects Exit
while (choice != -1) {
// printing menu
System.out.println("Select a method to run: ");
System.out.println("1. Method 1");
System.out.println("2. Method 2");
System.out.println("3. Method 3");
System.out.println("Enter -1 to exit");
System.out.print("Enter your choice: ");
// getting user input
choice = Integer.parseInt(sc.nextLine());
// according to input, selecting which method to run
if (choice == 1) {
printMessage1();
} else if (choice == 2) {
printMessage2();
} else if (choice == 3) {
printMessage3();
} else if (choice == -1) {
// if -1 selected, get out of the loop
break;
} else {
// if invalid input, then print error message.
System.out.println("Please enter a correct choice.");
}
}
// closing the scanner after running the complete program
sc.close();
}
// dummy method 1
public static void printMessage1() {
System.out.println("Selected Choice: " + 1);
}
// dummy method 2
public static void printMessage2() {
System.out.println("Selected Choice: " + 2);
}
// dummy method 3
public static void printMessage3() {
System.out.println("Selected Choice: " + 3);
}
}
Output
This is for assignment: Lab, Names: Bob and Bill
Select a method to run:
1. Method 1
2. Method 2
3. Method 3
Enter -1 to exit
Enter your choice: 1
Selected Choice: 1
Select a method to run:
1. Method 1
2. Method 2
3. Method 3
Enter -1 to exit
Enter your choice: 3
Selected Choice: 3
Select a method to run:
1. Method 1
2. Method 2
3. Method 3
Enter -1 to exit
Enter your choice: 2
Selected Choice: 2
Select a method to run:
1. Method 1
2. Method 2
3. Method 3
Enter -1 to exit
Enter your choice: 2
Selected Choice: 2
Select a method to run:
1. Method 1
2. Method 2
3. Method 3
Enter -1 to exit
Enter your choice: 3
Selected Choice: 3
Select a method to run:
1. Method 1
2. Method 2
3. Method 3
Enter -1 to exit
Enter your choice: 5
Please enter a correct choice.
Select a method to run:
1. Method 1
2. Method 2
3. Method 3
Enter -1 to exit
Enter your choice: 1
Selected Choice: 1
Select a method to run:
1. Method 1
2. Method 2
3. Method 3
Enter -1 to exit
Enter your choice: -1