2011-01-05 3 views
0

나는 한 달 넘게 판매 수치를 묻는 콘솔 응용 프로그램을 가지고 있습니다. 프로그램이 0 이하의 항목을 거부하도록하고 사용자에게 판매 수치를 다시 입력하도록 요청했습니다.유효하지 않은 문자에 대한 사용자 입력 확인

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(); 
     } 
    } 
} 

답변

0

아마 입력이 확인 정규 표현식을 사용하는 것이라고 생각 :하지만 지금은 사용자가 내가 현재 가지고있는 코드는 숫자가 아닌 문자 또는 다른 문자를 입력 할 때 같은 일이 발생 할 정확한 형태로.

4

Double.Parse을 사용하는 대신 Double.TryParse을 사용하십시오.이 숫자는 성공적으로 구문 분석되었는지 여부를 반환합니다.

더 나은 것은 Decimal.TryParse입니다. 통화 값에 double을 사용하지 않아야합니다.

추가 권장 사항 :

  • 당신은 하나 엄청난 방법을 가지고
  • .NET 명명 규칙을 준수 하나에 네임 스페이스를 수정 - 각각 하나 개의 작은 작업을 수행하는 여러 가지 방법으로 그것을 깰
  • 배열 대신 List<T>을 사용하는 것을 고려하십시오. 모든 것을 사전에 할당 할 필요가 없습니다.
  • v에 대해 특정 명명 규칙을 사용하지 않아도됩니다. ariables; 일반적으로 오히려 그러한 스트림 및 독자로 자원을 닫 방법의 상단에
  • 사용 using 문을 모든 선언보다 먼저 사용의 시점에서 지역 변수를 선언하는 것을 선호
  • 일관되게 좋은 것입니다. (현재 나는 당신이 이제까지 무엇이든을 닫습니다 생각하지 않습니다.)
+0

감사합니다. –

+0

double.tryparse는 '메서드에 대한 오버로드가 없습니다'라는 이유로 작동하지 않습니다. TryParse는 1 개의 인수를가집니다. 내가 완전한 초보자이기 때문에 설명 할 수 있는지 궁금해! 감사합니다 –

+0

나는이 사람들이 C++에서 온 것 같아요 :) – Sherwin

0

사용하는 대신 구문 분석의 TryParse : 교체

:

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에 대해.

+0

이 작동하지만 숫자 0 만 사용합니다. 내가 다시 판매 수치에 대한 사용자에게 물어보고 싶습니다 –

+0

@Stephen : 당신이 "isValidDouble 나중에 확인"제안대로 숫자 0을 사용하지 않습니다 ... –

관련 문제