首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从Console.ReadLine()检索变量

从Console.ReadLine()检索变量
EN

Software Engineering用户
提问于 2016-03-26 14:47:07
回答 1查看 763关注 0票数 0

我正在C#做一个抽搐脚趾游戏。每个方格都有一个字符串变量。我想要这样做,这样用户就可以输入正方形名称,即(topMiddle)。然后声明输入playerInput。我想使用str.Replace(‘','x');但是,我使用的不是str,而是框的名称,即(TopMiddle)。如何使用控制台输入检索该变量?

到目前为止,我的代码如下:

代码语言:javascript
复制
using System;

namespace TicTac_toe
{
public class CreateVariables
{
    public static void Main (string[] args)
    {
        string topRight = " ";
        string topMiddle = " ";
        string topLeft = " ";
        string middleLeft = " ";
        string center = " ";
        string middleRight = " ";
        string bottomLeft = " ";
        string bottomMiddle = " ";
        string bottomRight = " ";
        string line = "|";
        string dash = "_ _ _";
        string xInput;
        string oInput;
        bool player1;
        System.Console.WriteLine (topLeft + line + topMiddle + line + topRight + "\n" + dash + "\n" + "\n" + middleLeft + line + center + line + middleRight + "\n" + dash + "\n" + "\n" + bottomLeft + line + bottomMiddle + line + bottomRight);
        System.Console.WriteLine ("Player 1, it is your turn. WHat box will you mark?");
        xInput = System.Console.ReadLine ();
        topRight = xInput.Replace (' ', 'X');
        System.Console.Clear ();
        System.Console.WriteLine (topLeft + line + topMiddle + line + topRight + "\n" + dash + "\n" + "\n" + middleLeft + line + center + line + middleRight + "\n" + dash + "\n" + "\n" + bottomLeft + line + bottomMiddle + line + bottomRight);

对不起,如果我的代码混乱,我的问题是一个简单的修复。这是我使用c#的第四天,所以我还有很多东西要学。

EN

回答 1

Software Engineering用户

发布于 2016-03-26 19:26:47

您需要编写一个if语句,以确保使用用户的输入选择正确的变量名。在您的问题中,您可以声明ReadLine()存储在一个playerInput变量中,但是您的代码示例显示了两个名为xInput和oInput的变量。为了保持这个简单,我的答案使用了您在问题中提到的单个playerInput变量。例如:

代码语言:javascript
复制
if (playerInput == "topLeft")
{ 
   topLeft = "X";
}
else if (playerInput == "topMiddle")
{
   topMiddle = "X";
}
...
else if (playerInput == "bottomRight")
{
   bottomRight = "X";
}

这就是如何确保在程序中更新正确的变量的方法。与您在这里采用的方法相比,实现tic toe游戏的方法肯定更优雅,因此,在完成此工作之后,请考虑重申以使代码更简洁。

票数 -2
EN
页面原文内容由Software Engineering提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://softwareengineering.stackexchange.com/questions/313910

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档