if / if else / else

时间:2016-11-24 21:02:56

标签: c# if-statement

我是C#的新手并遇到以下问题。

计算车辆支付税的计划。用户输入汽车类型(有3种类型),许可证长度(6或12个月)和发射带(5种类型),程序打印出许可证的费用:

只要我选择6个月的许可证长度,我的代码就能完美运行。

请帮助我理解我犯了什么错误,谢谢。

static void Main(string[] args)
    {
        bool check;
        int car, length;
        double rate = 0;
        string band = "";


        Console.WriteLine("{0,-12} {1,-12} {2,-12}", "Diesel Car", "Petrol Car", "Alt. Fuel Car");
        Console.WriteLine("{0,-12} {1,-12} {2,-12}", "TC 49", "TC 48", "TC 59");

        Console.WriteLine("Enter Car Type (TC #): ");
        check = int.TryParse(Console.ReadLine(), out car);
        if (check)
        {
            if (car == 49)
            {

                    Console.WriteLine("Enter Licience length in months(6 or 12)");
                    length = int.Parse(Console.ReadLine());
                    if (length == 6)
                    {
                        Console.WriteLine("Enter Emission Band (AA, A, B, C, D): ");
                        band = Console.ReadLine();
                        if (band == "AA")
                        {
                            rate = 44;
                        }
                        else if (band == "A")
                        {
                            rate = 60.5;
                        }
                        else if (band == "B")
                        {
                            rate = 71.5;
                        }
                        else if (band == "C")
                        {
                            rate = 82.5;
                        }
                        else if (band == "D")
                        {
                            rate = 88;
                        }
                        else
                            Console.WriteLine("ERROR"); //error for band != AA,A,B,C or D

                    }
                    else if (length == 12)
                    {
                        if (band == "AA")
                        {
                            rate = 80;
                        }
                        else if (band == "A")
                        {
                            rate = 110;
                        }
                        else if (band == "B")
                        {
                            rate = 130;
                        }
                        else if (band == "C")
                        {
                            rate = 150;
                        }
                        else if (band == "D")
                        {
                            rate = 160;
                        }
                        else
                            Console.WriteLine("ERROR"); //error for band != AA,A,B,C or D 
                    }
                    else
                        Console.WriteLine("ERROR"); // error for length != 6 or 12

            }
            else if (car == 48)
            {
                Console.WriteLine("Enter Licience length in months(6 or 12)");
                length = int.Parse(Console.ReadLine());
                if (length == 6)
                {
                    Console.WriteLine("Enter Emission Band (AA, A, B, C, D): ");
                    band = Console.ReadLine();
                    if (band == "AA")
                    {
                        rate = 38.5;
                    }
                    else if (band == "A")
                    {
                        rate = 55;
                    }
                    else if (band == "B")
                    {
                        rate = 66;
                    }
                    else if (band == "C")
                    {
                        rate = 77;
                    }
                    else if (band == "D")
                    {
                        rate = 85.25;
                    }
                    else
                        Console.WriteLine("ERROR"); //error for band != AA,A,B,C or D

                }
                else if (length == 12)
                {
                    if (band == "AA")
                    {
                        rate = 70;
                    }
                    else if (band == "A")
                    {
                        rate = 100;
                    }
                    else if (band == "B")
                    {
                        rate = 120;
                    }
                    else if (band == "C")
                    {
                        rate = 140;
                    }
                    else if (band == "D")
                    {
                        rate = 155;
                    }
                    else
                        Console.WriteLine("ERROR"); //error for band != AA,A,B,C or D 
                }
                else
                    Console.WriteLine("ERROR"); // error for length != 6 or 12
            }
            else if (car == 59)
            {
                Console.WriteLine("Enter Licience length in months(6 or 12)");
                length = int.Parse(Console.ReadLine());
                if (length == 6)
                {
                    Console.WriteLine("Enter Emission Band (AA, A, B, C, D): ");
                    band = Console.ReadLine();
                    if (band == "AA")
                    {
                        rate = 33;
                    }
                    else if (band == "A")
                    {
                        rate = 49.5;
                    }
                    else if (band == "B")
                    {
                        rate = 60.5;
                    }
                    else if (band == "C")
                    {
                        rate = 71.5;
                    }
                    else if (band == "D")
                    {
                        rate = 82.5;
                    }
                    else
                        Console.WriteLine("ERROR"); //error for band != AA,A,B,C or D

                }
                else if (length == 12)
                {
                    if (band == "AA")
                    {
                        rate = 60;
                    }
                    else if (band == "A")
                    {
                        rate = 90;
                    }
                    else if (band == "B")
                    {
                        rate = 110;
                    }
                    else if (band == "C")
                    {
                        rate = 130;
                    }
                    else if (band == "D")
                    {
                        rate = 150;
                    }
                    else
                        Console.WriteLine("ERROR"); //error for band != AA,A,B,C or D 
                }
                else
                    Console.WriteLine("ERROR"); // error for length != 6 or 12
            }
            else
                Console.WriteLine("ERROR"); // error for car number != 48,49 or 59
        }
        else
            Console.WriteLine("ERROR"); //error for car num != int
        Console.WriteLine(rate);
    }

6 个答案:

答案 0 :(得分:3)

您的代码中存在多个问题作为概念,但您的问题无法解决的原因是:

if (length == 6)
{
    Console.WriteLine("Enter Emission Band (AA, A, B, C, D): ");
    band = Console.ReadLine();
    //..other stuff
}
else if (length == 12)
{
    //here band has his initial value
}

所以你需要询问if(length == 6)

之外的乐队

如何改进代码。嵌套if是非常糟糕的做法所以你应该总是考虑编写没有箭头结构的代码(嵌套if)。

public static void Main()
{
    int car = 0;
    int length = 0;
    Console.WriteLine("Enter Car Type (TC #): ");

    if(!int.TryParse(Console.ReadLine(), out car))
    {
        Console.WriteLine("Not valid number");
        return;
    }

     Console.WriteLine("Enter Licience length in months(6 or 12)");
     if(!int.TryParse(Console.ReadLine(), out length))
     {
         Console.WriteLine("Not valid number");
         return;
     }

     Console.WriteLine("Enter Emission Band (AA, A, B, C, D): ");
     string band = Console.ReadLine();

     Dictionary<Tuple<int,int,string>, decimal> carDataDic = GetCarDetails();

     decimal ratio = 0;

     Tuple<int, int, string> checkRatioKey = new Tuple<int, int, string>(car, length, band);

     if(!carDataDic.TryGetValue(checkRatioKey, out ratio))
     {
         Console.WriteLine("No value found for input data");
         return;
     }

     Console.WriteLine("Ratio is: " + ratio);
}

public static Dictionary<Tuple<int,int,string>, decimal> GetCarDetails()
{
     Dictionary<Tuple<int,int,string>, decimal> values= new Dictionary<Tuple<int,int,string>, decimal>();

     //Tuple Items -> Item1=car, Item2=length, Item3= band), value in Dictionary is the rate which you should have
     values.Add(new Tuple<int, int, string>(49, 6, "AA"), 44);
     values.Add(new Tuple<int, int, string>(49, 6, "A"), 60.5);
     //define all of your cases.

     return values;
}

Tuple具有一个类的角色,您可以在其中存储特定于汽车的数据。这很好用,因为您可以将它用于Dictionary中的键。

答案 1 :(得分:0)

var modelName = req.options.model.charAt(0).toUpperCase() + req.options.model.slice(1) var elementID = null if (req.params.id) { // To handle DELETE, PUT elementID = req.params.id } if (req.body.id) { // To handle POST elementID = req.body.id } this[modelName].findOne({ id: elementID }).exec(function(err, contextElement) { if(err) { return res.serverError(err) } if(contextElement.group=== req.user.group.id) { sails.log('accessing own: ' + modelName) return next() } else { return res.forbidden('Tried to access not owned object') } }) 的分支不会提示length == 12的值。您还需要在这些分支上复制该问题,或者更改您的代码以删除一些重复。

答案 2 :(得分:0)

您提供的代码中的问题:

当用户选择band时,您无法获得12的用户输入

尝试:

else if (length == 12)
{
    Console.WriteLine("Enter Emission Band (AA, A, B, C, D): ");
    band = Console.ReadLine();
    //etc ...

<强>改进:

编写代码(特别是在您提供的代码中)时,重要的是担心可读性,看看我们是否不需要重复代码。

正如众多评论所暗示的那样,编写代码的结构远非最佳。 Tuples已被提及,这当然是一种好方法。

我的示例演示了如何使用Car class来实现此目的,这是另一种可能的改进解决方案。

class Program
{
    public static List<Car> CarList;

    static void Main(string[] args)
    {

        PopulateCars();

        int car, length;
        decimal rate = 0m;
        Car.CarBand band;

        Console.WriteLine("{0,-12} {1,-12} {2,-12}", "Diesel Car", "Petrol Car", "Alt. Fuel Car");
        Console.WriteLine("{0,-12} {1,-12} {2,-12}", "TC 49", "TC 48", "TC 59");

        Console.WriteLine("Enter Car Type (TC #): ");
        var keyboardInput = Console.ReadLine();

        while (!int.TryParse(keyboardInput, out car))
        {
            Console.WriteLine("Invalid car input, try again.");
            keyboardInput = Console.ReadLine();
        }

        Console.WriteLine("Enter Licience length in months(6 or 12)");
        keyboardInput = Console.ReadLine();

        while (!int.TryParse(keyboardInput, out length))
        {
            Console.WriteLine("Invalid months input, try again.");
            keyboardInput = Console.ReadLine();
        }

        Console.WriteLine("Enter Emission Band (AA, A, B, C, D): ");
        keyboardInput = Console.ReadLine();

        while (!Enum.TryParse(keyboardInput, out band))
        {
            Console.WriteLine("Invalid band input, try again.");
            keyboardInput = Console.ReadLine();
        }

        var matchedCar = CarList.FirstOrDefault(c => c.CarNumber == car && c.Lenght == length && c.Band == band);

        if (matchedCar != null)
            Console.WriteLine("The rate for this car is {0}", matchedCar.Rate);
        else
            Console.WriteLine("Car not found");

        Console.ReadLine();

    }

    public class Car
    {
        public int CarNumber { get; set; }
        public int Lenght { get; set; }
        public CarBand Band { get; set; }
        public decimal Rate { get; set; }

        public enum CarBand
        {
            AA,
            A,
            B,
            C,
            D
        }
    }

    public static void PopulateCars()
    {
        CarList = new List<Car>();

        // Cars 48
        CarList.Add(new Car { CarNumber = 48, Lenght = 6, Band = Car.CarBand.AA, Rate = 38.5m });
        CarList.Add(new Car { CarNumber = 48, Lenght = 6, Band = Car.CarBand.A, Rate = 55m });
        CarList.Add(new Car { CarNumber = 48, Lenght = 6, Band = Car.CarBand.B, Rate = 66m });
        CarList.Add(new Car { CarNumber = 48, Lenght = 6, Band = Car.CarBand.C, Rate = 77m });
        CarList.Add(new Car { CarNumber = 48, Lenght = 6, Band = Car.CarBand.D, Rate = 85.25m });

        CarList.Add(new Car { CarNumber = 48, Lenght = 12, Band = Car.CarBand.AA, Rate = 70m });
        CarList.Add(new Car { CarNumber = 48, Lenght = 12, Band = Car.CarBand.A, Rate = 100m });
        CarList.Add(new Car { CarNumber = 48, Lenght = 12, Band = Car.CarBand.B, Rate = 120m });
        CarList.Add(new Car { CarNumber = 48, Lenght = 12, Band = Car.CarBand.C, Rate = 140m });
        CarList.Add(new Car { CarNumber = 48, Lenght = 12, Band = Car.CarBand.D, Rate = 155m });

        //Cars 49
        CarList.Add(new Car { CarNumber = 49, Lenght = 6, Band = Car.CarBand.AA, Rate = 44m });
        CarList.Add(new Car { CarNumber = 49, Lenght = 6, Band = Car.CarBand.A, Rate = 60.5m });
        CarList.Add(new Car { CarNumber = 49, Lenght = 6, Band = Car.CarBand.B, Rate = 71.5m });
        CarList.Add(new Car { CarNumber = 49, Lenght = 6, Band = Car.CarBand.C, Rate = 82.5m });
        CarList.Add(new Car { CarNumber = 49, Lenght = 6, Band = Car.CarBand.D, Rate = 88m });

        CarList.Add(new Car { CarNumber = 49, Lenght = 12, Band = Car.CarBand.AA, Rate = 80m });
        CarList.Add(new Car { CarNumber = 49, Lenght = 12, Band = Car.CarBand.A, Rate = 110m });
        CarList.Add(new Car { CarNumber = 49, Lenght = 12, Band = Car.CarBand.B, Rate = 130m});
        CarList.Add(new Car { CarNumber = 49, Lenght = 12, Band = Car.CarBand.C, Rate = 150m });
        CarList.Add(new Car { CarNumber = 49, Lenght = 12, Band = Car.CarBand.D, Rate = 160m });           

        // Cars 59
        CarList.Add(new Car { CarNumber = 59, Lenght = 6, Band = Car.CarBand.AA, Rate = 33m });
        CarList.Add(new Car { CarNumber = 59, Lenght = 6, Band = Car.CarBand.A, Rate = 49.5m });
        CarList.Add(new Car { CarNumber = 59, Lenght = 6, Band = Car.CarBand.B, Rate = 60.5m });
        CarList.Add(new Car { CarNumber = 59, Lenght = 6, Band = Car.CarBand.C, Rate = 71.5m });
        CarList.Add(new Car { CarNumber = 59, Lenght = 6, Band = Car.CarBand.D, Rate = 82.5m });

        CarList.Add(new Car { CarNumber = 59, Lenght = 12, Band = Car.CarBand.AA, Rate = 60m });
        CarList.Add(new Car { CarNumber = 59, Lenght = 12, Band = Car.CarBand.A, Rate = 90m });
        CarList.Add(new Car { CarNumber = 59, Lenght = 12, Band = Car.CarBand.B, Rate = 110m });
        CarList.Add(new Car { CarNumber = 59, Lenght = 12, Band = Car.CarBand.C, Rate = 130m });
        CarList.Add(new Car { CarNumber = 59, Lenght = 12, Band = Car.CarBand.D, Rate = 150m });        
    }

}

答案 3 :(得分:0)

你没有在12个月的许可证长度条件下输入排放频带.bool check;             整车,长度;             双倍率= 0;             string band =&#34;&#34 ;;

        Console.WriteLine("{0,-12} {1,-12} {2,-12}", "Diesel Car", "Petrol Car", "Alt. Fuel Car");
        Console.WriteLine("{0,-12} {1,-12} {2,-12}", "TC 49", "TC 48", "TC 59");

        Console.WriteLine("Enter Car Type (TC #): ");
        check = int.TryParse(Console.ReadLine(), out car);
        if (check)
        {
            if (car == 49)
            {

                Console.WriteLine("Enter Licience length in months(6 or 12)");
                length = int.Parse(Console.ReadLine());
                if (length == 6)
                {
                    Console.WriteLine("Enter Emission Band (AA, A, B, C, D): ");
                    band = Console.ReadLine();
                    if (band == "AA")
                    {
                        rate = 44;
                    }
                    else if (band == "A")
                    {
                        rate = 60.5;
                    }
                    else if (band == "B")
                    {
                        rate = 71.5;
                    }
                    else if (band == "C")
                    {
                        rate = 82.5;
                    }
                    else if (band == "D")
                    {
                        rate = 88;
                    }
                    else
                        Console.WriteLine("ERROR"); //error for band != AA,A,B,C or D

                }
                else if (length == 12)
                {
                    Console.WriteLine("Enter Emission Band (AA, A, B, C, D): ");
                    band = Console.ReadLine();
                    if (band == "AA")
                    {
                        rate = 80;
                    }
                    else if (band == "A")
                    {
                        rate = 110;
                    }
                    else if (band == "B")
                    {
                        rate = 130;
                    }
                    else if (band == "C")
                    {
                        rate = 150;
                    }
                    else if (band == "D")
                    {
                        rate = 160;
                    }
                    else
                        Console.WriteLine("ERROR"); //error for band != AA,A,B,C or D 
                }
                else
                    Console.WriteLine("ERROR"); // error for length != 6 or 12

            }
            else if (car == 48)
            {
                Console.WriteLine("Enter Licience length in months(6 or 12)");
                length = int.Parse(Console.ReadLine());
                if (length == 6)
                {
                    Console.WriteLine("Enter Emission Band (AA, A, B, C, D): ");
                    band = Console.ReadLine();
                    if (band == "AA")
                    {
                        rate = 38.5;
                    }
                    else if (band == "A")
                    {
                        rate = 55;
                    }
                    else if (band == "B")
                    {
                        rate = 66;
                    }
                    else if (band == "C")
                    {
                        rate = 77;
                    }
                    else if (band == "D")
                    {
                        rate = 85.25;
                    }
                    else
                        Console.WriteLine("ERROR"); //error for band != AA,A,B,C or D

                }
                else if (length == 12)
                {
                    Console.WriteLine("Enter Emission Band (AA, A, B, C, D): ");
                    band = Console.ReadLine();
                    if (band == "AA")
                    {
                        rate = 70;
                    }
                    else if (band == "A")
                    {
                        rate = 100;
                    }
                    else if (band == "B")
                    {
                        rate = 120;
                    }
                    else if (band == "C")
                    {
                        rate = 140;
                    }
                    else if (band == "D")
                    {
                        rate = 155;
                    }
                    else
                        Console.WriteLine("ERROR"); //error for band != AA,A,B,C or D 
                }
                else
                    Console.WriteLine("ERROR"); // error for length != 6 or 12
            }
            else if (car == 59)
            {
                Console.WriteLine("Enter Licience length in months(6 or 12)");
                length = int.Parse(Console.ReadLine());
                if (length == 6)
                {
                    Console.WriteLine("Enter Emission Band (AA, A, B, C, D): ");
                    band = Console.ReadLine();
                    if (band == "AA")
                    {
                        rate = 33;
                    }
                    else if (band == "A")
                    {
                        rate = 49.5;
                    }
                    else if (band == "B")
                    {
                        rate = 60.5;
                    }
                    else if (band == "C")
                    {
                        rate = 71.5;
                    }
                    else if (band == "D")
                    {
                        rate = 82.5;
                    }
                    else
                        Console.WriteLine("ERROR"); //error for band != AA,A,B,C or D

                }
                else if (length == 12)
                {
                    Console.WriteLine("Enter Emission Band (AA, A, B, C, D): ");
                    band = Console.ReadLine();
                    if (band == "AA")
                    {
                        rate = 60;
                    }
                    else if (band == "A")
                    {
                        rate = 90;
                    }
                    else if (band == "B")
                    {
                        rate = 110;
                    }
                    else if (band == "C")
                    {
                        rate = 130;
                    }
                    else if (band == "D")
                    {
                        rate = 150;
                    }
                    else
                        Console.WriteLine("ERROR"); //error for band != AA,A,B,C or D 
                }
                else
                    Console.WriteLine("ERROR"); // error for length != 6 or 12
            }
            else
                Console.WriteLine("ERROR"); // error for car number != 48,49 or 59
        }
        else
            Console.WriteLine("ERROR"); //error for car num != int
        Console.WriteLine(rate);
        Console.ReadLine();`

答案 4 :(得分:0)

更好的代码可能如下所示:

// Dictionary from (car,length,band) to rate
static readonly Dictionary<Tuple<int, int, string>, decimal> rates =
  new Dictionary<Tuple<int, int, string>, decimal>
  {
    { Tuple.Create(49, 6, "AA"), 44m },
    { Tuple.Create(49, 6, "A"), 60.5m },
    { Tuple.Create(49, 6, "B"), 71.5m },
    { Tuple.Create(49, 6, "C"), 82.5m },
    { Tuple.Create(49, 6, "D"), 88m },
    { Tuple.Create(49, 12, "AA"), 80m },
    { Tuple.Create(49, 12, "A"), 110m },
    { Tuple.Create(49, 12, "B"), 130m },
    { Tuple.Create(49, 12, "C"), 150m },
    { Tuple.Create(49, 12, "D"), 160m },
    { Tuple.Create(48, 6, "AA"), 38.5m },
    { Tuple.Create(48, 6, "A"), 55m },
    { Tuple.Create(48, 6, "B"), 66m },
    { Tuple.Create(48, 6, "C"), 77m },
    { Tuple.Create(48, 6, "D"), 85.25m },
    { Tuple.Create(48, 12, "AA"), 70m },
    { Tuple.Create(48, 12, "A"), 100m },
    { Tuple.Create(48, 12, "B"), 120m },
    { Tuple.Create(48, 12, "C"), 140m },
    { Tuple.Create(48, 12, "D"), 155m },
    { Tuple.Create(59, 6, "AA"), 33m },
    { Tuple.Create(59, 6, "A"), 49.5m },
    { Tuple.Create(59, 6, "B"), 60.5m },
    { Tuple.Create(59, 6, "C"), 71.5m },
    { Tuple.Create(59, 6, "D"), 82.5m },
    { Tuple.Create(59, 12, "AA"), 60m },
    { Tuple.Create(59, 12, "A"), 90m },
    { Tuple.Create(59, 12, "B"), 110m },
    { Tuple.Create(59, 12, "C"), 130m },
    { Tuple.Create(59, 12, "D"), 150m },
  };

static void Main()
{
  Console.WriteLine("Diesel Car   Petrol Car   Alt. Fuel Car");
  Console.WriteLine("TC 49        TC 48        TC 59");
  Console.WriteLine("Enter Car Type (TC #): ");
  int car;
  if (!int.TryParse(Console.ReadLine(), out car))
  {
    Console.WriteLine("Error");
    return;
  }

  Console.WriteLine("Enter Licience length in months(6 or 12)");
  int length;
  if (!int.TryParse(Console.ReadLine(), out length))
  {
    Console.WriteLine("Error");
    return;
  }

  Console.WriteLine("Enter Emission Band (AA, A, B, C, D): ");
  string band = Console.ReadLine();

  var key = Tuple.Create(car, length, band);
  decimal rate;
  if (!rates.TryGetValue(key, out rate)
  {
    Console.WriteLine("Error finding rate for " + key);
    return;
  }
  Console.WriteLine(rate);
}

这与mybirthname在答案中的建议基本相同。

备注:在即将到来的C#7.0(预计2017年)中,我认为元组的语法会更好。

答案 5 :(得分:-1)

如果是if else,则使用switch关键字代替此问题