我如何找到一个特定的数字

时间:2018-07-14 12:35:04

标签: c#

我正在尝试创建7个BOOM游戏。如果您不了解规则,每个人都会轮流说出下一个数字,但是如果该数字可以除以7或包含7,则应该改为BOOM。因此,在我的版本中,您插入一个数字,程序将显示该点的所有数字。

这是我的问题,我成功实现了第一部分,但是第二部分却遇到了问题。这是我到目前为止所拥有的:

class Program
{
    static void Main(string[] args)
    {
        int num1 = int.Parse(Console.ReadLine());
        int num2 = 0;
        bool boolean;
        while (num1>num2)
        {
            num2++;
            if (num2%7 == 0)
            {
                Console.Write("BOOM, ");
            }
            else
            {
                Console.Write(num2 + ", ");
            }
        }
    }
}

2 个答案:

答案 0 :(得分:1)

只需将您的验证更改为:

if (num2%7 == 0 || num2.ToString().IndexOf('7') != -1)
{
  // (..)
}

IndexOf函数查找并返回子字符串在字符串中的位置。如果找不到,则返回-1。

@Dimitry指出,另一种选择是

if (num2%7 == 0 || num2.ToString().Contains('7'))
{
  // (..)
}

这使用扩展方法Contains,如果子字符串存在于字符串中,则返回true或false。

答案 1 :(得分:0)

public static void Main()
{
    Console.Write("Please enter a number: ");
    int number = int.Parse(Console.ReadLine());

    // validate number here....

    for (int i = 1; i <= number; i++)
    {
        string value = IsMultipleOrContains7(i) ? "BOOM" : i.ToString();

        Console.WriteLine(value);
    }

    Console.WriteLine("Press any key to continue...");
    Console.ReadKey();
}

public static bool IsMultipleOrContains7(int number)
{
    if (number % 7 == 0)
    {
        return true;
    }

    return number.ToString().Contains("7");
}
相关问题