首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >第一个C#项目。我在错误处理方面有困难。并使用尝试/捕捉。如果有人能看一看,那就很有意义了。:)

第一个C#项目。我在错误处理方面有困难。并使用尝试/捕捉。如果有人能看一看,那就很有意义了。:)
EN

Stack Overflow用户
提问于 2021-04-25 02:56:22
回答 1查看 76关注 0票数 1

https://github.com/FaisalRana/CSharp.Bakery <--这是我回购的链接。

最近,我使用以下提示启动了一个项目:在c#中创建一个面包店,用户可以从那里订购面包或糕点。该程序根据菜单输出总价。

我正在学习测试驱动的开发,我能够成功地编写我的测试和函数,并遵循红色绿色重构工作流。

此外,通过使用if语句,我能够处理输入负数的错误。当某人输入一个字符串而不是他们的订单输入的整数时,我试图做错误处理。但

如果(输入(输入) !==整数){} <--这在c#中不起作用。在控制台中输入非int输入时所遇到的错误:

处理异常。System.FormatException: Input string was not in a correct format.

谢谢

代码语言:javascript
复制
using System;
using System.Collections.Generic;

namespace Bakery.Models
{
  public class Program
  {
    public static void Main()
    {
      Console.ForegroundColor = ConsoleColor.DarkGray;
      Console.BackgroundColor = ConsoleColor.Blue;
      Console.WriteLine("Welcome to Brother Lasif's Bakery!");
      string bakeryAscii = @"
                          ....
                      .'      `.
                    .' .-'``-._ `.
                    |  / -    - ` |
                    / |'<o>  <o> | \
                  | (|    '`    |) |
                  |   \  -==-  /   |
                  |    `.____.'    |
                  \     |    |     |
                  _\_.'`-.__.-'`._/_
                .'| |`-.  /\  .-'| |`.
              _.'   \ \  `'  `'  / /   `._
            { `.    | `-.____.-' |    .' }
            /`. `./ /   __  __   \ \.' .'\
            /   `.| |   /  \/  \   | |.'   \
          (    (  \ \  \      /  / /  )    )
            `.   \  Y|   `.  .'   |Y  /   .'
              \   \ ||_ _ _\/_ _ _|| /   /
              `.  \|'            `|/  .'
        _______/  _ >--------------< _  \______.##._
              ((((_(                )_))))   .##. |
            / ```` `--------------' ''''\   |  | |
            (                             \  |  |-'
            )                             ) `--'
            (          _        _.---.__.-'
            `-.___.--' `------'

        ";
      Console.WriteLine(bakeryAscii);
      Console.WriteLine("Please [y] to place your order, [m] to view the menu and [n] to exit");
      string  continueAnswer = Console.ReadLine().ToLower();
      if (continueAnswer == "y") {
          Console.WriteLine("How many loaves of bread would you like to purchase today?");
          int breadInput = Convert.ToInt32(Console.ReadLine()); 
            if (breadInput > 0 ) {
              Bread testBread = new Bread();
              int breadPrice = testBread.CalcBread(breadInput);
              Console.WriteLine("You have bought " + breadInput + " loaves of bread for: $" + breadPrice);
              Console.WriteLine("Would you like to buy some Pastry's today? [y] or [n]");
              string pastryAnswer = Console.ReadLine().ToLower();
              if (pastryAnswer == "y") {
                Console.WriteLine("Please enter the amount of pastry's you would like to buy:");
                int pastryInput = Convert.ToInt32(Console.ReadLine()); 
                  if (pastryInput >= 0) {
                    Pastry testPastry = new Pastry();
                    int pastryPrice = testPastry.CalcPastry(pastryInput);
                    Console.WriteLine("You have bought " + pastryInput + " pastry's");
                    Console.BackgroundColor = ConsoleColor.DarkGray;
                    Console.ForegroundColor = ConsoleColor.Green;
                    Console.WriteLine("Your total bill is $" + breadPrice + pastryPrice);
                } 
                  else {            
                  negativeNumberError();    
                } 

                  } 
                  else if (pastryAnswer == "n") {
                    Console.WriteLine("Thank you for Coming in, your total bill is $" + breadPrice);
                    Console.WriteLine("Goodbye");
                  }
  
            } else {   
              negativeNumberError();      
            }
      } else if (continueAnswer == "m") {
        Menu();
    } else if (continueAnswer == "n") {
      Console.WriteLine("Goodbye");
    } else {
      Console.WriteLine("Invalid Input");
      Main();
    }
}

    public static void Menu() {
      Console.WriteLine("--------------------------------");
        string menu = @"Fresh Bread: $5 each (loaf)
        Delicious Pastry: $2 each

        ** Special of the week **
        Bread: Buy 2, get 1 free!
        Pastry: 3 for $5!";
        Console.WriteLine(menu);
        Console.WriteLine("--------------------------------");
        Console.WriteLine("Press enter to continue");
        string menuAnswer = Console.ReadLine();
        Main();
    }
        public static void negativeNumberError() {
          Console.ForegroundColor = ConsoleColor.Red;
          Console.WriteLine("Error, please try again and enter a number greater than 0");
          Console.ReadLine();
          Main();
    }
    }
}
EN

回答 1

Stack Overflow用户

发布于 2021-04-25 03:41:38

而不是

int breadInput = Convert.ToInt32(Console.ReadLine());

你可能需要类似的东西

代码语言:javascript
复制
int breadInput;
do
{
    Console.WriteLine("How many loaves of bread would you like to purchase today?");
}
while (!int.TryParse(Console.ReadLine(), out breadInput));

我选择了do...while,而不是 (而则更常见),因为在评估响应之前,我们需要问这个问题。

如果我选择while,那么我将不得不重复WriteLine行。让我们来试试while

代码语言:javascript
复制
Console.WriteLine("How many loaves of bread would you like to purchase today?");

int breadInput;
while (!int.TryParse(Console.ReadLine(), out breadInput));
{
    Console.WriteLine("How many loaves of bread would you like to purchase today?");
}

这并不漂亮,但最大的问题是,有一天我可以在一个地方修改这个问题,然后忘记更新第二个WriteLine

<1

请注意,while内部的条件可以扩展到处理负数。任何可以进入if内部的东西都可以进入while

代码语言:javascript
复制
while (!int.TryParse(Console.ReadLine(), out breadInput) || (breadInput <= 0));

辅助方法

我鼓励您创建一个可以重用的助手方法。这将使你的主要逻辑看起来清晰。下面是一个例子:

代码语言:javascript
复制
// Concise code I can reuse for multiple questions
var ok = AskPositiveInt("How many loaves of bread would you like to purchase today?"
 , max: 100
 , out int breadInput);
if(!ok) 
{
   // todo  
}

(...)

static bool AskPositiveInt(string question, int max, out int number )
{
    // Here we can add as much validation as we wish
    Console.WriteLine(question);

    int numberOfTries = 5; //Number of tries before giving up
    for( int i = 0; i < numberOfTries; i++ )
    {
        
        var answer = Console.ReadLine();

        if(!int.TryParse(answer, out number))
        {
            Console.WriteLine("Please provide a number.");
            continue; // go back to 'for'
        } 

        if (number <= 0)
        {
            Console.WriteLine("Please provide a number.");
            continue; // go back to 'for'
        }

        if (number > max)
        {
            Console.WriteLine($"Insufficient stock. Please provide a number <{max}");
            continue; // go back to 'for'
        }

        //Everything OK
        return true;
    }
    
    number = 0;
    return false;
}

错误处理

在代码中,可以在Main处理程序中调用negativeNumberError

这不会长期有效,因为您永远不会离开原始的Main

如果这个数字一直是负数,那么你将添加到主链->Main中。你必须想出一个更好的策略。

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67249339

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档