简体   繁体   English

C#代码验证程序

[英]C# Code Verification Program

Alright so I am making a program to verify a 4 digit code. 好吧,所以我正在编写一个程序来验证4位数字的代码。

The computer generates a 4 digit code The user types in a 4 digit code. 计算机生成一个4位代码。用户输入4位代码。 Their guess. 他们的猜测。 the computer tells them how many digits are guessed correctly in the correct place and how many digits have been guessed correctly but in the wrong place. 计算机会告诉他们在正确的位置正确猜测了多少位数,在错误的位置正确猜测了多少位数。 The user gets 12 guesses to either win – guess the right code. 用户将赢得12个猜中任何一个,即猜出正确的代码。 Or lose – run out of guesses. 还是输-用尽猜测。

So basically, my program doesn't seem to actually verify whether the code is correct but i cant see why not because i have if and for loops for verification, please take a look. 因此,基本上,我的程序似乎并未实际验证代码是否正确,但我看不到为什么,因为我有if和for循环进行验证,请看一下。

class Program
{
    public static Random random = new Random();
    static void Main(string[] args)
    {
        int DigitOne = random.Next(0, 10);
        int DigitTwo = random.Next(0, 10);
        int DigitThree = random.Next(0, 10);
        int DigitFour = random.Next(0, 10);

        byte[] code = new byte[4];
        code[0] = Convert.ToByte(DigitOne);
        code[1] = Convert.ToByte(DigitTwo);
        code[2] = Convert.ToByte(DigitThree);
        code[3] = Convert.ToByte(DigitFour);
        bool CodeCorrect = false;
        Console.WriteLine(code[0] +""+ code[1] +""+ code[2]+""+code [3] );

        Console.WriteLine("You have 12 guesses before you will be permenantly locked out.\n");
        int AmountOfGuesses = 0;
        while (AmountOfGuesses < 12 && !CodeCorrect)
        {
            Console.WriteLine("Enter 4 digit code to unlock the safe: ");
            int[] UserCode = new int[4];

            for (int i = 0; i < 4; i++)
            {
                UserCode[i] = Convert.ToInt32(Console.Read()) - 48;
            }
            if (UserCode.Length != 4)
            {
                Console.WriteLine("Error. Try Again.\n");
            }
            else
            {
                int UserDigitOne = UserCode[0];
                int UserDigitTwo = UserCode[1];
                int UserDigitThree = UserCode[2];
                int UserDigitFour = UserCode[3];
                for (int i = 0; i < 4; i++)
                {
                    if (UserCode[i] == code[i])
                    {
                        Console.WriteLine("The digit at position " + (i + 1) + " is correct.");
                    }
                }  


                if (UserCode[0] == code[0] && UserCode[1] == code[1] && UserCode[2] == code[2] && UserCode[3] == code[3])
                {
                    CodeCorrect = true;
                    Console.WriteLine("Code Correct. Safe unlocked.");

                }
            }



            AmountOfGuesses++;
        }

        if (AmountOfGuesses > 12)
        {
            Console.WriteLine("Code Incorrect. Safe Locked permenantly.");
        }

        Console.ReadLine();

    }

You are comparing numbers with the character representation of a number. 您正在将数字与数字的字符表示进行比较。 Each value of code[] represents an actual number. code[]每个值代表一个实际数字。 You then compare those values with the values in UserCode which is a string, meaning there is a character at each index. 然后,您将这些值与UserCode中的值进行UserCode ,后者是一个字符串,这意味着每个索引处都有一个字符。 It is never the case that ((byte)'4') == ((byte)4) (using 4 as an example, but works for any numerical digit). ((byte)'4') == ((byte)4)从来都不是这种情况(以4为例,但适用于任何数字)。

One way around this is to parse each user input character into a byte using the byte.Parse method. 解决此问题的一种方法是使用byte.Parse方法将每个用户输入字符解析为一个字节。


For fun learning purposes look at the output from the following code: 为了有趣的学习目的,请看以下代码的输出:

for (char i = '0'; i <= '9'; i++)
{
    Console.WriteLine("char: " + i + "; value: " + ((byte)i));
}

The output is actually: 输出实际上是:

char: 0; value: 48
char: 1; value: 49
char: 2; value: 50
char: 3; value: 51
char: 4; value: 52
char: 5; value: 53
char: 6; value: 54
char: 7; value: 55
char: 8; value: 56
char: 9; value: 57

This is due to string encoding. 这是由于字符串编码。

I would also recommend that one you have your code working that you submit it to the fine folks at the Code Review site to review other aspects of the code which could use work. 我还建议您使您的代码有效,然后将其提交给“ 代码审查”站点上的高级人员,以审查可能使用工作的代码的其他方面。

If you step through the code after it generated the number 1246, and then input the same number from the command line, convert it to a char array, then convert each char to a byte, you'll get the following four bytes: 如果在生成数字1246之后逐步执行代码,然后从命令行输入相同的数字,将其转换为char数组,然后将每个char转换为一个字节,则将获得以下四个字节:

49 50 52 54 49 50 52 54

These correspond to the ASCII representations of each char, NOT the actual numbers. 这些对应于每个字符的ASCII表示,而不是实际数字。

Try something like this: 尝试这样的事情:

int[] input = new int[4];

for(int i = 0; i < 4; i++ )
{
    input[i] = Convert.ToInt32(Console.Read()) - 48;
}

The -48 should turn your ASCII code into the actual numerical representation that was provided. -48应该将您的ASCII代码转换为提供的实际数字表示形式。 Console.Read() reads individual characters rather than the full line. Console.Read()读取单个字符而不是整行。

Also, you don't have to say: 另外,您不必说:

CodeCorrect == false

This is more simply represented as: 更简单地表示为:

!CodeCorrect

Similarly, if it was set to true, it would just be: 同样,如果将其设置为true,则将是:

CodeCorrect 

I also suggest using a for loop to set multiple elements in an array rather than manually writing out each line of code. 我还建议使用for循环在数组中设置多个元素,而不是手动写出每一行代码。 It's not a big deal for small arrays, but it's good practice. 对于小型阵列来说,这没什么大不了的,但这是一个好习惯。

UPDATE: Here's a revised version of the full program: 更新:这是完整程序的修订版:

class Program 
{ 
    public static Random random = new Random(); 
    static void Main(string[] args) 
    {
        int[] randCombination = new int[4];
        for (int i = 0; i < 4; i++)
        {
            randCombination[i] = random.Next(0, 10);
            Console.Write(randCombination[i].ToString());
        }
        bool CodeCorrect = false;

        Console.WriteLine("\nYou have 12 guesses before you will be permenantly locked out.\n");

        int AmountOfGuesses = 0;
        while(AmountOfGuesses < 12 && !CodeCorrect)
        {
            Console.WriteLine("Enter 4 digit code to unlock the safe: ");

            int[] UserCode = new int[4];
            string input = Console.ReadLine();

            int n;
            bool isNumeric = int.TryParse(input, out n);

            int correctCount = 0;

            if(input.Length != 4 || !isNumeric)
            {
                Console.WriteLine("Error. Input code was not a 4 digit number.\n");
            }
            else 
            {
                for(int i = 0; i < 4; i++)
                {
                    UserCode[i] = Convert.ToInt32(input[i]) - 48;

                    if(UserCode[i] == randCombination[i])
                    {
                        Console.WriteLine("The digit at position " + (i + 1) + " is correct.");
                        correctCount++;
                    }
                }

                if(correctCount == 4)
                {
                    CodeCorrect = true;
                    Console.WriteLine("Code Correct. Safe unlocked.");
                }
            }
            AmountOfGuesses++;
        }

        if(AmountOfGuesses >= 12)
        {
            Console.WriteLine("Code Incorrect. Safe Locked permenantly.");
        }

        Console.ReadLine();
    }
}

A couple of things were changed: 有几处更改:

  • Added a for loop at the top that generates a random number, enters it into an array of ints and then prints it to standard output. 在顶部添加了一个for循环,该循环生成一个随机数,将其输入一个整数数组,然后将其打印到标准输出中。
  • I changed the way user input is read back to the Console.ReadLine() . 我更改了将用户输入读回Console.ReadLine() The reason for this is to check if the user inputted a four digit integer. 这样做的原因是检查用户是否输入了四位数的整数。 the int.TryParse statement makes sure the input is an int, and the Length property checks the length. int.TryParse语句确保输入为int,并且Length属性检查长度。
  • I also used a counter to count each correct guess. 我还使用了一个计数器来计算每个正确的猜测。 If 4 correct digit guesses were made, the safe is unlocked. 如果做出了4位正确的猜测,则保险箱将被解锁。
  • Your final if statement would never have evaluated because Amount of Guesses would equal 12, not be greater than it. 您的最终if语句永远不会求值,因为Guesses的数量等于12,不能大于12。 Changed it to >= from >. 将其从>更改为> =。 Always be on the lookout for small things like this. 始终注意这种小事情。

EDIT #2: For more information on int.TryParse, see the following: 编辑#2:有关int.TryParse的更多信息,请参见以下内容:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM