【问题标题】:When Input Values To My Program, It Crashes :( C# [duplicate]当我的程序输入值时,它崩溃:( C# [重复]
【发布时间】:2019-05-30 11:01:38
【问题描述】:

这是程序。有人可以告诉我我做错了什么吗?每次我为字符串 SolvingFor 输入一个值时,程序就会崩溃。我是编码新手,所以如果我犯了一个愚蠢的错误,请告诉我。

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

namespace PercentageCalculator
{
class Program
{
    static void Main(string[] args)
    {
        string SolvingFor;
        int part;
        int whole;
        int percent;
        Console.WriteLine("please only use numbers and lowercase letters.");
        Console.WriteLine("Are you trying to solve for percent, part, or           whole?");
         SolvingFor = Convert.ToString(Console.Read());

        if (SolvingFor == "part") {
            Console.WriteLine("Please Enter Value of the Whole");
            whole = Convert.ToInt32(Console.ReadLine());
            Console.WriteLine("Please Enter Value of the Percent");
            percent = Convert.ToInt32(Console.ReadLine()); ;
            Console.WriteLine("Your answer is" + (whole * percent) / 100); }

       else if (SolvingFor == "whole")
        {
            Console.WriteLine("Please Enter Value of the part");
            part = Convert.ToInt32(Console.ReadLine());
            Console.WriteLine("Please Enter Value of the Percent");
            percent = Convert.ToInt32(Console.ReadLine()); ;
            Console.WriteLine("Your answer is" + (part * 100) / percent);
        }


        else if (SolvingFor == "percent")
        {
            Console.WriteLine("Please Enter Value of the part");
            part = Convert.ToInt32(Console.ReadLine());
            Console.WriteLine("Please Enter Value of the whole");
            whole = Convert.ToInt32(Console.ReadLine()); ;
            Console.WriteLine("Your answer is" + (part * 100) / whole);
        }

        else
        {
            Console.WriteLine("Please only input valid lowercase letters and numbers. ");
        };
        Console.Read();
    }
    }
}

【问题讨论】:

  • 什么是异常,发生在哪一行?始终包含错误信息。它们不仅仅是为了好玩,它们会告诉您出了什么问题,而且通常还会告诉您原因。
  • 而不是使用Convert.ToInt32() 来解析用户输入以获得一个int。您应该使用int.TryParse()。当您可以期待异常时,请避免异常。 (从不信任用户输入)
  • 这似乎解决了它

标签: c#


【解决方案1】:
        //SolvingFor = Convert.ToString(Console.Read());
        SolvingFor = Convert.ToString(Console.ReadLine());

如果您将鼠标悬停在 ReadLine 上

你会看到它返回一个字符串,所以不需要 Convert.ToString

        SolvingFor = Console.ReadLine();

【讨论】:

  • 不需要Convert.ToString()
  • @J.vanLangen 是的
【解决方案2】:

第一期: 您的代码的下面一行只读取一个字符。

代替Console.Read(),使用Console.ReadLine() 可以让您输入多个字符。

 SolvingFor = Convert.ToString(Console.Read());

第二期: 你正在使用Convert.ToInt32(Console.Readline());

请注意,Convert.ToInt32 将在除数字以外的任何内容作为输入时引发异常。

最好使用int.TryParse,它会在转换成功与否时返回。

【讨论】:

    猜你喜欢
    • 2012-08-07
    • 1970-01-01
    • 2015-07-20
    • 1970-01-01
    • 1970-01-01
    • 2021-06-17
    • 2021-10-13
    • 2011-05-09
    • 2017-05-22
    相关资源
    最近更新 更多