-2

This is the program. Can someone tell me what I did wrong? Every time I input a value for the string SolvingFor, the program crashes. I'm new to coding so if I made a stupid mistake please tell me.

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();
    }
    }
}
Sebastian Hofmann
  • 1,440
  • 6
  • 15
  • 21

2 Answers2

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

if you put(hover) the mouse over ReadLine

enter image description here

you will see that it returns a string so Convert.ToString is not needed

        SolvingFor = Console.ReadLine();
Mohamed Elrashid
  • 8,125
  • 6
  • 31
  • 46
1

First Issue: Below line from your code is reading just one character.

Instead of Console.Read(), use Console.ReadLine() to enable you to input multiple characters.

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

Second Issue: You are using Convert.ToInt32(Console.Readline());

Please note that Convert.ToInt32 will throw an exception in anything apart from number is provided as input.

Better use int.TryParse which returns if the conversion is successful or not.

Sebastian Hofmann
  • 1,440
  • 6
  • 15
  • 21
Manoj Choudhari
  • 5,277
  • 2
  • 26
  • 37