如何在If语句中使用Console.Readline [英] How Do I Use A Console.Readline In An If Statement

查看:136
本文介绍了如何在If语句中使用Console.Readline的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好。我正在尝试使用控制台应用程序在c#中制作像龙与地下城这样的游戏。我试图使用带有readlines的if语句,它不会让我。这是我输入的代码。



  if (控制台) .ReadLine ==( 攻击))
{
// 从地精中夺走健康。
}

解决方案

对于初学者来说,问题非常简单:ReadLine是一种方法,这意味着您需要通过附加可以放置参数的括号来将其作为方法来调用in:

  if (Console.ReadLine()==  攻击
{
// 从精灵身上带走健康。
}

但我还是不会这样做。

原因为什么不是很简单:如果它是扔或失控呢?如果您不保存用户输入,则之后无法测试其他任何内容。

因此,请阅读输入,然后检查它:

< pre lang =cs> string userResponse = Console.ReadLine();
if (userResponse == Attack
{
// 从地精中夺走健康。
}
else if (userResponse == 失控
}
...



我也不会这样做! :笑:

  string  userResponse = Console.ReadLine(); 
switch (userResponse.ToLower())
{
case attack
// 从精灵身上夺走健康。
...
break ;
case 失控
// 运行aaaaaaway!
...
< span class =code-keyword> break :
默认
Console.WriteLine( 对不起,我不明白!);
break ;
}

尝试一下 - 你应该会发现它更容易阅读。


Hello. I am trying to make a game like dungeons and dragons in c# using a console application. I am trying to use if statements with readlines and it won't let me. this is the code that i put in.

if(Console.ReadLine == ("Attack"))
{
    //Take away health from the goblin.
}

解决方案

For starters, the problem is pretty simple: ReadLine is a method, and that means you need to call it as a method by appending brackets that you could put parameters in:

if(Console.ReadLine() == "Attack")
{
    //Take away health from the goblin.
}

But I woudln't do that anyway.
The reason why not is pretty simple: what if it's "throw" or "runaway" instead? Becasue you don't save the user input, you can't test it for anything else afterwards.
So instead, read teh input, and then check it:

string userResponse = Console.ReadLine();
if (userResponse == "Attack")
{
    //Take away health from the goblin.
}
else if (userResponse == "Runaway")
}
    ...


And I wouldn't do it like that either! :laugh:

string userResponse = Console.ReadLine();
switch (userResponse.ToLower())
    {
    case "attack":
        //Take away health from the goblin.
        ...
        break;
    case "runaway":
        // Run aaaaaaway!
        ...
        break:
    default:
        Console.WriteLine("I'm sorry, I didn't understand that!");
        break;
    }

Try it - you should find it's easier to read.


这篇关于如何在If语句中使用Console.Readline的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆