【问题标题】:Why does my code skip my Console.Read after the first one?为什么我的代码在第一个代码之后跳过了我的 Console.Read?
【发布时间】:2015-02-28 07:41:20
【问题描述】:

好的,这就是我所拥有的,控制台运行并接受任何数字作为第一个输入并输出所有输出,但它会跳过第一个之后的其余读取。我是 C# 的新手,想学习,所以我绝对觉得我在这里错过了一些愚蠢的东西。不要担心目的,因为我只需要帮助解决我现在面临的这个问题。

谢谢大家,

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Stamps
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello, and welcome to the U.S. Mail Stamp Printer. Now, to print the correct stamp for your postage, please enter the number of half ounces (so 1= .5 ounce, 2 = 1 ounce) your package will weigh \n");
            double i = Console.Read();

            Console.WriteLine("Thank you, now, will you be sending to zone 1, 2, or 3? Simply enter the zone number and press enter\n");
            double z = Console.Read();

            Console.WriteLine("Great! Now, last question before I print your stamp, will you be using Local Mail or Air Mail, use the number 1 for local and the number 2 for air.\n");
            double m = Console.Read();


            if (m == 2)
            {
                double m2 = .95;


            }
            else
            {
                double m2 = .49;
            }


            if( i == 1)
            {
               double i2 = 1;
            }



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

【问题讨论】:

    标签: c# input user-input skip


    【解决方案1】:

    Console.Read method 不解析输入,它只从输入流中读取一个字符。

    使用Console.ReadLine method 并解析你得到的字符串:

    double i = Double.Parse(Console.ReadLine());
    

    或:

    int z = Int32.Parse(Console.ReadLine());
    

    如果您想处理无效输入,您可以使用 TryParse 方法,它们将返回一个布尔值,告诉您解析是否有效。


    旁注:当您尝试使用m2i2 变量时,您会注意到它不存在。该变量对于if 语句中的代码块是本地的,因此您需要在外部声明它以便以后能够使用它:

    double m2;
    if (m == 2)
    {
      m2 = .95;
    }
    else
    {
      m2 = .49;
    }
    

    【讨论】:

    • 非常感谢,我会在今天下午开始工作,但这很有意义!
    【解决方案2】:

    您可以刷新控制台缓冲区,也可以使用 console.readline()。

    有关更多信息,请参阅下面给出您问题答案的帖子。

    http://stackoverflow.com/questions/7302544/flushing-system-console-read
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-05-10
      • 2020-02-27
      • 2017-09-19
      • 2015-06-03
      • 2017-02-05
      • 1970-01-01
      • 2021-03-07
      • 1970-01-01
      相关资源
      最近更新 更多