有人可以帮我解决,我的if else语句不起作用

时间:2020-05-08 20:37:30

标签: c#

我有以下代码,但我不知道我在哪里做错了,目标是:当用户键入r或s或q时 它将触发相应的功能。但是,它仅适用于第一个字母

using System;


public class dice
{
int count = 0;
static void roll()
{
   Console.WriteLine("roll") ;
}
static void status() 
{
    Console.WriteLine("status") ;
}
public void Menu()
{
    Console.WriteLine("Please enter a command(r - roll, s - status, q- quit):");
    if (Console.ReadLine().Equals("r"))
    {
        roll();
    }
    else if (Console.ReadLine().Equals("s"))
    {
        status();
    }
    else if (Console.ReadLine().Equals("q"))
    {
        Console.WriteLine("Thanks for playing");
    }
    }
    }
   class program
   {


   public static void Main()
   {


    dice player = new dice();
    player.Menu();
   }
   }

3 个答案:

答案 0 :(得分:6)

一次读取 并将结果存储在变量中:

var input = Console.ReadLine();

然后在测试中使用该变量。

并使用循环,这是完成此类控制台菜单的常用便捷方式。

while(true) // The loop exits on "break" statement.
{
    Console.WriteLine("Please enter a command(r - roll, s - status, q- quit):");
    var input = Console.ReadLine();

    if (input == "r")
    {
        roll();
    }
    else if (input == "s")
    {
        status();
    }
    else if (input == "q")
    {
        Console.WriteLine("Thanks for playing");
        break;
    }
} 

答案 1 :(得分:1)

我喜欢Pac0's解决方案,但如果您只检查单字符输入,我个人会坚持使用Console.ReadKey()而不是Console.ReadLine()

这看起来像:

Console.WriteLine("Please enter a command(r - roll, s - status, q- quit):");

var pressedKey = Console.ReadKey().Key;
if (pressedKey == ConsoleKey.R)
{
    roll();
}
else if (pressedKey == ConsoleKey.S)
{
    status();
}
else if (pressedKey == ConsoleKey.Q)
{
    Console.WriteLine("Thanks for playing");
}

答案 2 :(得分:-1)

考虑当前保存所有用户输入的缓冲区。当您使用Console.ReadLine()时,它将从输入中移出一个字符并将其与第一个字母进行比较。 然后,当您第二次使用Console.ReadLine时,它将显示用户的第二个输入,该输入不存在。

domains = ['gmail.com','hotmail']
#scrape elements
ff = webdriver.Firefox(executable_path="D:/Programas/gecko/geckodriver.exe")

for domain in domains:
    ff.get('https://instantdomainsearch.com/pt/#search='+ domain)
    html = ff.page_source
    soup = BeautifulSoup(html,'html.parser')
    list_ = soup.find('div', {'class':'awrzayw'})
    elements = list_.find('a')

    try:
       elements = list_.find('a')
    except:
       elements = "comprar"

    for element in elements:
       print(element)

也就是说,将用户输入内容放在另一个变量中并与之进行比较。