首页 > 解决方案 > 当向我的程序输入值时,它会崩溃:( C#

问题描述

这是程序。有人可以告诉我我做错了什么吗?每次我为字符串 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();
    }
    }
}

标签: c#

解决方案


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

如果您将鼠标悬停在 ReadLine 上

在此处输入图像描述

您会看到它返回一个字符串,因此不需要Convert.ToString

        SolvingFor = Console.ReadLine();

推荐阅读