【发布时间】:2020-11-22 14:03:58
【问题描述】:
我正在用 C# 制作石头、剪纸、剪刀游戏,目前在有人输入不是 R、S 或 P 的输入时尝试显示消息时遇到问题。例如,我正在尝试获取默认值在 switch 语句中工作,但我没有运气。这是我目前拥有的。如果我有任何其他问题,请告诉我。
using System;
namespace Rockpaperscissors
{
class Program
{
static void Main(string[] args)
{
string inputPlayer, Computer;
int randomnum;
string loop;
bool keepPlaying = true;
while (keepPlaying)
{
int wins = 0;
int Loses = 0;
int ties = 0;
while (keepPlaying)
{
Random myRandomObject = new Random();
randomnum = myRandomObject.Next(1, 4);
Console.Write("To play: enter R for Rock, S for Scissors, P for Paper.");
inputPlayer = Console.ReadLine();
inputPlayer = inputPlayer.ToUpper();
switch (randomnum)
{
case 1:
Computer = "Rock";
Console.WriteLine("The computer played Rock");
if (inputPlayer == "R")
{
Console.WriteLine("Tie!!\n\n");
ties++;
}
else if (inputPlayer == "P")
{
Console.WriteLine("You win!!\n\n");
wins++;
}
else if (inputPlayer == "S")
{
Console.WriteLine("Computer wins!!\n\n");
Loses++;
}
break;
case 2:
Computer = "Paper";
Console.WriteLine("The computer played Paper");
if (inputPlayer == "P")
{
Console.WriteLine("Tie!!\n\n");
ties++;
}
else if (inputPlayer == "R")
{
Console.WriteLine("Computer wins!!\n\n");
Loses++;
}
else if (inputPlayer == "S")
{
Console.WriteLine("You win!!\n\n");
wins++;
}
break;
case 3:
Computer = "Scissors";
Console.WriteLine("The computer played Scissors");
if (inputPlayer == "S")
{
Console.WriteLine("Tie!!\n\n");
ties++;
}
else if (inputPlayer == "R")
{
Console.WriteLine("You win!!\n\n");
wins++;
}
else if (inputPlayer == "P")
{
Console.WriteLine("Computer wins!!\n\n");
Loses++;
}
break;
default:
Console.WriteLine("Please enter a correct entry");
break;
}
Console.WriteLine("Scores:\tWins:\t{0},\tLoses:\t{1},\tties:\t{2}", wins, Loses, ties);
Console.WriteLine("Would you like to continue playing? (y/n)");
loop = Console.ReadLine();
if (loop == "y")
{
keepPlaying = true;
}
else if (loop == "n")
{
keepPlaying = false;
}
else
{
}
}
}
}
}
}
请帮忙!
【问题讨论】:
-
switch 语句不直接处理用户输入,因此不清楚您期望默认情况如何与之有任何关系。仅当开关进入其他情况之一时才检查用户输入。如果这样做,那么它将不会进入默认值。在这些不同的情况下,你有很多重复的代码。
-
你学会并可以使用Function/Method了吗?
-
另外,您似乎有两个 while 循环检查同一个变量,但也不确定这应该是什么。
-
看看我对这个问题的回答:stackoverflow.com/questions/53746727/…。不是控制台应用,但逻辑应该是一样的
-
myRandomObject.Next(1, 4) 只会返回 1、2 或 3。因此不会达到默认情况。
标签: c#