【问题标题】:Checking user input for invalid characters检查用户输入的无效字符
【发布时间】:2011-01-05 13:35:10
【问题描述】:

我有一个控制台应用程序,它会询问用户一个月内的销售数据。我已经让程序拒绝低于零的条目,并要求用户再次输入他们的销售数字。但是现在我希望当用户输入一个字母或任何其他不是数字的字符时发生同样的事情我目前拥有的代码是:

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

namespace FIRST_ACTUAL_PROJECT
{
    class Program
    {
        static void Main(string[] args)
        {
            FileStream fin; // this is declaring that you are using a filestream.
            String s;
            int LineNum = 0;
            double seventy_percent_value;
            double thirty_percent_value;
            const int max_num_of_items = 20; // this means that there will always be a maximum of 20 sales figures because there is a maximum of 20 customers
            double[] sales_figures = new double[max_num_of_items]; // this is the array for the sales figures
            string[] customer = new string[max_num_of_items]; // this is the array for the customers
            double[] licence_fee_in_percent = new double[max_num_of_items]; // this is the array for the licence fee 
            double[] fee_payable = new double[max_num_of_items]; // array for the fees payable in pounds.
            const double MIN_SALES_FIGURE = 0;
            try
            {
                fin = new FileStream("customer list.txt", FileMode.Open);// this is opening the file.
            }
            catch (IOException exc)
            {
                Console.WriteLine(exc.Message + "cannot find file!"); // error message if it does'nt find the file or something went wrong.
                Console.ReadLine();
                return;
            }
            StreamReader fstr_in = new StreamReader(fin); // this is telling the streamreader which file to read.
            try
            {
                while ((s = fstr_in.ReadLine()) != null) // this is reading the file until the end.
                {
                    Console.WriteLine(s);
                    customer[LineNum] = s.Split(',')[0];
                    licence_fee_in_percent[LineNum] = double.Parse(s.Split(',')[1]);
                    LineNum = LineNum + 1;
                }
            }
            catch (IOException exc)
            {
                Console.WriteLine(exc.Message);
            }
            for (int CustPos = 0; CustPos < LineNum; CustPos = CustPos + 1) // this determines what the loop does.
            {
                Console.Write("enter sales figures for" + customer[CustPos] + "  "); // this asks the user to enter the sales figures
                sales_figures[CustPos] = Double.Parse(Console.ReadLine()); // this is user's input is read in and stored.

                while (sales_figures[CustPos] < MIN_SALES_FIGURE)   // this is if the user enters a number below zero.
                {
                    Console.WriteLine("");
                    Console.WriteLine("entry invalid");
                    Console.WriteLine("");
                    Console.WriteLine("enter sales figures for" + customer[CustPos] + "  ");
                    sales_figures[CustPos] = Double.Parse(Console.ReadLine());
                }

                    Console.WriteLine(" ");
                    fee_payable[CustPos] = (sales_figures[CustPos] / 100.0) * licence_fee_in_percent[CustPos];
                    Console.WriteLine(customer[CustPos] + " ----------- " + fee_payable[CustPos]);
                    Console.WriteLine("Licence fee to be paid in GBP is :" + fee_payable[CustPos]);         //this section displays the cust name, sales figure 70/30.
                    seventy_percent_value = ((fee_payable[CustPos] / 10.0) * 7);
                    Console.WriteLine("70 percent of this fee is" + seventy_percent_value);
                    thirty_percent_value = ((fee_payable[CustPos] / 10.0) * 3);
                    Console.WriteLine("30 percent of this fee is" + thirty_percent_value);
                    Console.WriteLine(" ");
                }

            }
            Console.WriteLine("Customer name" + "\t" + "sales" + "\t" + "fee paid" + "\t" + "70% value" + "\t" + "30% value" + "\t");
            for (int DisplayPos = 0; DisplayPos < LineNum; DisplayPos = DisplayPos + 1)
            {
                seventy_percent_value = ((fee_payable[DisplayPos] / 10.0) * 7);
                thirty_percent_value = ((fee_payable[DisplayPos] / 10.0) * 3);
                Console.WriteLine(customer[DisplayPos] + "\t" + sales_figures[DisplayPos] + "\t" + fee_payable[DisplayPos] + "\t\t" + seventy_percent_value + " \t\t" + thirty_percent_value + "\t");
            }
            Console.WriteLine(" ");
            Console.WriteLine("Press enter to finish");
            Console.ReadLine();
        }
    }
}

【问题讨论】:

    标签: c# validation console-application


    【解决方案1】:

    不要使用Double.Parse,而是使用Double.TryParse - 这将返回号码是否解析成功。

    更好的是,使用Decimal.TryParse - 您不应该使用double 来表示货币值。

    其他建议:

    • 将命名空间修复为符合 .NET 命名约定的命名空间
    • 你有一个巨大的方法 - 将它分解成几个方法,每个方法执行一个小任务
    • 考虑使用 List&lt;T&gt; 而不是数组 - 这样您就不需要预先分配所有内容
    • 您的变量没有任何特定的命名约定;保持一致会很好
    • 通常更喜欢在首次使用时声明局部变量,而不是在方法顶部声明所有内容
    • 使用using 语句关闭您的资源,例如流和阅读器。 (目前我认为你永远不会关闭任何东西。)

    【讨论】:

    • double.tryparse 不起作用,因为它说“方法 'TryParse' 没有重载需要 1 个参数”。只是想知道您是否可以解释一下,因为我是一个完整的初学者!谢谢
    • 我认为这些家伙来自 c++ :)
    • @Stephen:Double.TryParse 接受解析值的“out”参数并返回它是否成功。有关示例,请参阅文档:msdn.microsoft.com/en-us/library/994c0zb1.aspx。正如我所说,你应该使用小数。
    【解决方案2】:

    我认为可能会使用正则表达式来检查输入是否正确。

    【讨论】:

      【解决方案3】:

      使用 TryParse 代替 Parse:

      替换:

       sales_figures[CustPos] = Double.Parse(Console.ReadLine()); // this is user's input is read in and stored.
      

      与:

       bool isValidDouble = Double.TryParse(Console.ReadLine(), out sales_figures[CustPos] );
      

      然后检查 isValidDouble。

      【讨论】:

      • 这可行,但它只使用数字零。我希望它重新向用户询问销售数据
      • @Stephen:如果您按照建议“稍后检查 isValidDouble”,它将不会使用数字零...
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-26
      • 2016-03-28
      • 1970-01-01
      相关资源
      最近更新 更多