如何防止控制台阅读“输入”按钮在我能够输入我的号码之前进入它? [英] How do I keep the console from reading the "Enter" entered into it before I am able to type in my number?

查看:90
本文介绍了如何防止控制台阅读“输入”按钮在我能够输入我的号码之前进入它?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

namespace Exercise3New
{
    class Program
    {
        static void Main(string[] args)
        {
            int monthNumber;

            //Prompt for number
            Console.Write("Enter a number between 1 and 12");
            monthNumber = int.Parse(Console.ReadLine());





当我去运行程序时,我无法输入我的号码,因为这样做我必须在命令提示符下按Enter键,它只是在我按下回车时读取它。



When I go to run the program I am unable to enter in my number because to do so I must push enter in the command prompt and it just reads it as me pushing enter.

推荐答案

也许这会对你有所帮助;这是在控制台中获取条目的一种非常标准的方式,检查条目是否有效(在这种情况下条目是'整数),并且如果条目无效则重复输入过程。
Maybe this will help you; it's a pretty standard way of getting entry in the Console, checking the entry is valid (in this case that the entry is an 'integer), and repeating the entry process if the entry is not valid.
using System;

namespace YourNameSpace
{
    class Program
    {
        static void Main(string[] args)
        {
            const int MinValue = 1;
            const int MaxValue = 12;
    
            int entryValue;
    
            Console.WriteLine("\nEnter a number between 1~{0}: ", MaxValue);
            if (! Int32.TryParse(Console.ReadLine(), out entryValue))
            {
                Console.Clear();
                Console.WriteLine("Error: invalid number ... try again");
                Main(null);
            }
            else
            {
                if (entryValue < MinValue || entryValue > MaxValue)
                {
                    Console.Clear();
                    Console.WriteLine("Error: number out of range ... try again");
                    Main(null);
                }
            }
 
            // now you have a valid number in 'entryValue
            // do something with it ...
        }
    }
}

当然,这个代码示例没有显示的是相当标准的使用while循环来保持Console应用程序运行直到用户做什么来终止它,比如按下'Escape键。

Of course, what this code example doesn't show is the fairly standard use of a while-loop to keep the Console app running until the user does something to terminate it, like pressing the 'Escape key.


这篇关于如何防止控制台阅读“输入”按钮在我能够输入我的号码之前进入它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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