gpt4 book ai didi

c# - 我怎样才能在 switch 语句中有一个案例,让用户输入要显示的字符串

转载 作者:太空宇宙 更新时间:2023-11-03 21:17:02 25 4
gpt4 key购买 nike

所以我得到了这段代码。我有它,所以当用户输入数字 1-4 时,它会根据他们输入的数字在开头显示不同的说法和他们的名字。我想要做的是,当他们输入 -1 而不是 1、2、3 或 4 时,它允许他们输入自己的语句来输出。

using System;

namespace TryIt
{
class Conversation
{
// Declare constants that define the input range
private const int MIN = -1;
private const int MAX = 4;

// Declare constants for the colors to be used
private const ConsoleColor INPUT_COLOR = ConsoleColor.Green;
private const ConsoleColor PROMPT_COLOR = ConsoleColor.Blue;
private const ConsoleColor ERROR_COLOR = ConsoleColor.Red;
private const ConsoleColor MESSAGE_COLOR = ConsoleColor.White;
private const ConsoleColor BACKGROUND_COLOR = ConsoleColor.DarkGray;

private String name;

public Conversation()
{
Console.Title = "The Best TryIt Program";
Console.BackgroundColor = BACKGROUND_COLOR;
Console.Clear();
}

public void go()
{
getName();
int number = getNumber();
displayMessage(number);

Console.ForegroundColor = ConsoleColor.Gray;
Console.WriteLine();
}

private void getName()
{
Console.ForegroundColor = PROMPT_COLOR;
Console.Write("Enter your name. ");
Console.ForegroundColor = INPUT_COLOR;

// This will ask what your name is and prompt you to enter it.
name = Console.ReadLine();
}

private int getNumber()
{
int input;

// int input will take your name and display it back to you
do
{
Console.ForegroundColor = PROMPT_COLOR;
Console.Write("\nEnter a number from 1 to 4. ");
Console.ForegroundColor = INPUT_COLOR;

// This will ask you for a number
input = Convert.ToInt16(System.Console.ReadLine());

// If you don't put in a valid number it will tell you
if (input < MIN || input > MAX)
{
Console.ForegroundColor = ERROR_COLOR;
Console.WriteLine("Invalid Number!");
}
} while (input < MIN || input > MAX);

return input;
}

private void displayMessage(int choice)
{
String phrase = " ";

// Declares the variable (a string) for the output messages.
switch (choice)
{
case 1: phrase = " is a genius!"; break;
case 2: phrase = " is amazing!"; break;
case 3: phrase = " came to chew bubblegum" +
", kick butt " + "and is all out of gum."; break;
case 4: phrase = " is a rockstar!"; break;
}


Console.WriteLine();
Console.ForegroundColor = MESSAGE_COLOR;

// This will display the message you selected 10 times
for (int counter = 0; counter < 10; counter++)
{
Console.WriteLine(counter + ") " + name + phrase);
}
}
}

最佳答案

switch(choice)
{
case 1: ...
.
.
.
case -1: Console.WriteLine("Put in your own saying: ");
phrase = " " + Console.ReadLine();
break;
}

这个 switch case 会在输入“-1”时询问你是否输入谚语,然后将其写入短语。在 switch case 之后,您可以像上面的代码一样继续。

关于c# - 我怎样才能在 switch 语句中有一个案例,让用户输入要显示的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33480255/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com