Home > other >  C# passing variables through methods, and converting string to int with method
C# passing variables through methods, and converting string to int with method

Time:10-02

I am having trouble with this project. The project is to use user input to take scores. Using a loop that allows the user to input as many scores that they want. I am having a difficult time passing a variable to my ConvertToInt method. I am wanting to pass the variable, with the value, score to the ConvertToInt method. In the ConvertToInt method I have to convert the string to an int. What I have coded now will run but after entering a score the System.FormatException is thrown. I am new to C# and do not quite understand what is wrong.

using System;

namespace MethodsAndUnitTestsMethodTestsCampbell
{
    class Program
    {
        private static string GetUserInput(string scores)
        {
            Console.WriteLine("Enter score: ");
            string score = Console.ReadLine();
            score = scores;
            return score;
        }

        private static int ConvertToInt(string scores)
        {
            return Convert.ToInt32(scores);
        }

        static void Main(string[] args)
        {
            string scores = "{C} ";
            GetUserInput(scores);
            ConvertToInt(scores);
            

        }
    }
}

CodePudding user response:

You are not assigning the return value of GetUserInput method to scores variable. Below is updated program -

class Program
{
   private static int ConvertToInt(string scores)
   {
       return Convert.ToInt32(scores);
   }
   private static string GetUserInput(string scores) 
   { 
       Console.WriteLine("Enter score: "); 
       scores = Console.ReadLine();            
       return scores; 
   }

   static void Main(string[] args)
   {
       string scores = "{C} ";
       scores = GetUserInput(scores);
       ConvertToInt(scores);
   }
}

CodePudding user response:

You can use Int32.TryParse(String, Int32) to convert the string. Your code will be like this:

class Program
{
    private static void ConvertToInt32(string input, ref int output)
    {
        if (int.TryParse(input, out int number))
        {
            output = number;
        }
        else
        {
            System.Console.WriteLine($"Cannot convert {input}.");
        }
    }

    private static string GetUserInput(string prompt)
    {
        System.Console.Write(prompt);
        return System.Console.ReadLine();
    }

    static void Main(string[] args)
    {
        string input = GetUserInput("Enter scores: ");
        int scores = 0;
        ConvertToInt32(input, ref scores);
        System.Console.WriteLine($"Scores: {scores}");
    }
}
  • Related