如何从控制台读取连续的输入行以用于Add()方法?

时间:2013-04-09 13:51:02

标签: c# methods console-application readline

以下是我的代码:

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

namespace JeffOrrisSimpleCalculator._1
{
    class Program
    {
        static void Main(string[] args)
        {

            Console.WriteLine("Simple Calculator");
            Console.WriteLine("\t1> Add");
            Console.WriteLine("\t2> Subtract");
            Console.WriteLine("\t3> Multiply");
            Console.WriteLine("\t4> Divide");
            Console.WriteLine("\t5> Quit");
            Console.WriteLine();
            Console.Write("Enter Selection:  ");

            string myValue = ValidateData();
            Console.WriteLine(myValue);

            Console.Write("Enter number one:  ");
            Console.ReadLine();
            Console.Write("Enter number two:  ");
            Console.ReadLine();

            string mySum = Add();
            Console.WriteLine(mySum);

            Console.Read();
        }//end main

        private static string ValidateData()
        {


            string temp = Console.ReadLine();
            if ((temp == "1") || (temp == "2") || (temp == "3") || (temp == "4") ||                (temp == "5"))
            {
                //string Response = "Thank You";
                //return Response;

                return null;
            }
            else
            {
                string Response = "Please enter a valid selection";
                return Response;

            }
        }//end ValidateData



        private static string Add()
        {
            string numberOne = Console.ReadLine();
            double temp1 = Convert.ToDouble(numberOne);

            string numberTwo = Console.ReadLine();
            double temp2 = Convert.ToDouble(numberTwo);

            double total = temp1 + number2;
            string myTotal = Convert.ToString(total);
            return myTotal;
        }


        }//end class
        }//end namespace

*我只关心add方法。我提示用户输入我需要使用add方法添加的2个数字。我相信我过度思考这一点。我习惯于Windows窗体而不是控制台应用程序。我无法弄清楚如何从Console.ReadLine中连续保存这些输入变量。

1 个答案:

答案 0 :(得分:4)

  

我提示用户输入2个数字

是的,你正在提示用户 - 但是你完全忽略了他们的输入。这样:

Console.Write("Enter number one:  ");
Console.ReadLine();
Console.Write("Enter number two:  ");
Console.ReadLine();

应该更像是:

Console.Write("Enter number one:  ");
string firstLine = Console.ReadLine();
Console.Write("Enter number two:  ");
string secondLine = Console.ReadLine();

接下来,您需要了解如何将字符串转换为数字。查看该步骤的int.TryParse等。

(您可能需要在询问“第二个”之前验证“第一个” - 考虑创建一个方法,该方法接受一个提示字符串并一直提示用户,直到他们实际输入一个数字 - 然后从该方法返回。 )