Write the following code using c #,2. Modify your main so that the above method is call repeatedly. The program will terminate when the user enters 0.Any other choice should produce an error message. Because you will not be doing any arithmetic you may accept the user response either as an int, or a char or a string.
时间: 2024-02-12 14:08:29 浏览: 114
Sure, here's the C# code for your requirements:
```
using System;
class MainClass {
static void Main() {
string userInput;
int choice;
do {
Console.WriteLine("Enter a choice (1-4, or 0 to exit): ");
userInput = Console.ReadLine();
if (int.TryParse(userInput, out choice)) {
switch (choice) {
case 1:
Console.WriteLine("You chose option 1");
break;
case 2:
Console.WriteLine("You chose option 2");
break;
case 3:
Console.WriteLine("You chose option 3");
break;
case 4:
Console.WriteLine("You chose option 4");
break;
case 0:
Console.WriteLine("Exiting program...");
break;
default:
Console.WriteLine("Invalid choice. Please enter a number between 0 and 4.");
break;
}
} else {
Console.WriteLine("Invalid input. Please enter a number between 0 and 4.");
}
} while (choice != 0);
}
}
```
This program prompts the user to enter a choice between 1 and 4, or 0 to exit. It then uses a switch statement to handle the user's input and display the corresponding message. If the user enters an invalid input, the program displays an error message and prompts the user to try again. The program will keep running until the user enters 0 to exit.
阅读全文