Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/305.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 编写只接受int作为输入的int-to-hex转换器_C# - Fatal编程技术网

C# 编写只接受int作为输入的int-to-hex转换器

C# 编写只接受int作为输入的int-to-hex转换器,c#,C#,我一直在想如何添加一个循环来控制ReadLine只接受一个要转换的整数值的输入。我使用if/else转换输入,使用TryParse-else提示用户只输入Int值。然后我提出了一个do/while循环,试图让它一直请求输入,直到添加了Int,但它不会将userInput转换为hex。所以我回到了原点,我仍然感到困惑。如果输入了Int以外的任何内容,我如何防止它抛出异常,同时还不断询问,直到满足该条件?这将产生运行时所描述的行为 你认为“它不会将用户输入转换为十六进制”是什么意思?一些输入和输出示

我一直在想如何添加一个循环来控制ReadLine只接受一个要转换的整数值的输入。我使用if/else转换输入,使用TryParse-else提示用户只输入Int值。然后我提出了一个do/while循环,试图让它一直请求输入,直到添加了Int,但它不会将userInput转换为hex。所以我回到了原点,我仍然感到困惑。如果输入了Int以外的任何内容,我如何防止它抛出异常,同时还不断询问,直到满足该条件?

这将产生运行时所描述的行为


你认为“它不会将用户输入转换为十六进制”是什么意思?一些输入和输出示例可能有助于我们帮助您。可能会显示您对TryParse的尝试。
Int32.TryParse()
如果(!int.TryParse(userInput,out num)else Console.WriteLine(“仅输入一个int值:”)输入“ok”,则使用或者提示输入其他条目的单个字符。但例如输入8888将不会返回其十六进制等效值。使用代码Jawi,它将返回十六进制值。但是如果输入“ok”例如,如果输入一个有效的整数,它返回的字符超出了时间限制。输入一个有效的整数后,期望的行为是什么?永久输入循环,还是应该有一个字符终止程序永久循环,直到输入一个整数进行转换,然后程序在输出十六进制等效值时终止。非常感谢!我已经结束了t我很高兴能包含一个if-else。我真的很感谢你的反馈。
namespace HexConverter
{
    class HexConverter
    {
        static void Main(string[] args)
        {
            Console.WriteLine("I/O Hex Converter");
            GetUserInput();
            Console.ReadLine();
        }
        private static void GetUserInput()
        {
            Console.WriteLine("Enter Int value: ");

            int userInput = Convert.ToInt32(Console.ReadLine());

            Console.WriteLine("{0} Converted to Hex is: {0:X}", userInput);
        }
    }
}
using System;
namespace HexConverter
{
    class HexConverter
    {
        static void Main(string[] args)
        {
            Console.WriteLine("I/O Hex Converter");
            GetUserInput();
            Console.ReadLine();
        }
        private static void GetUserInput()
        {
            string userInput;
            int candidateNum;
            do
            {
                Console.WriteLine("Enter Int Value: ");
                userInput = Console.ReadLine();
            } while(!int.TryParse(userInput, out candidateNum));

            Console.WriteLine("{0} Converted to Hex is: {0:X}", candidateNum);
        }
    }
}