C # метод второй параметр необязательно - PullRequest
0 голосов
/ 01 декабря 2018

Я новичок в C #.

текущий неполный код

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

namespace classObjectMethodBasic
{
    public class Program
    {
        static void Main()
        {
            Console.WriteLine("Input a number for first number to do a math on: ");
            int number1 = Convert.ToInt32(Console.ReadLine());

            Console.WriteLine("Input a number for second number to do a math on or you need not enter one: ");
            int number2 = Convert.ToInt32(Console.ReadLine());

            int result1 = new int();
            result1 = Math.math(number1, number2);

            Console.WriteLine("Math result: " + result1);
            Console.ReadLine();
        }
    }
    public class Math
    {
        public static int math(int number1, int number2 = 3)
        {
            int result1 = number1 + number2;
            return result1;
        }
    }
}

Необходимо сделать второй параметр (номер2) необязательным.В текущем коде, если я запускаю его, но не ввожу значение для int number2 (означает просто нажать Enter), программа завершает работу с исключением, что имеет смысл.Ошибка исключения:

System.FormatException: 'Input string was not in a correct format.'

Как заставить программу работать со вторым параметром в качестве необязательного?

Спасибо, Джерри

Ответы [ 2 ]

0 голосов
/ 01 декабря 2018

Изменение вашего кода для проверки ввода, которое он получил, было бы лучше в целом.В вашем случае вы, вероятно, не вводите значение для второго значения, см. Исправления ниже

    static void Main()
    {
        Console.WriteLine("Input a number for first number to do a math on: ");
        int number1 = 0;
        string input1 = Console.ReadLine();
        if (!Int32.TryParse(input1, out number1))
        {
            Console.WriteLine("Number 1 was entered incorrectly");
            Console.ReadLine();
            return;
        }


        Console.WriteLine("Input a number for second number to do a math on or you need not enter one: ");
        int number2 = 0;
        string input2 = Console.ReadLine();


        if (input2.Equals(string.Empty))
        {
            Console.WriteLine("Math result: " + Math.math(number1));
        }
        else
        {
            if (!Int32.TryParse(input2, out number2))
            {
                Console.WriteLine("Number 2 was entered incorrectly");
                Console.ReadLine();
                return;
            }
            else
            {
                Console.WriteLine("Math result: " + Math.math(number1, number2));
            }
        }

        Console.ReadLine();
    }
0 голосов
/ 01 декабря 2018

Вы уже объявили второй параметр как необязательный.Ошибка связана с этой строкой кода:

 int number2 = Convert.ToInt32(Console.ReadLine());

Либо вы можете изменить свой код для проверки обоих параметров перед вызовом функции Math.math(), либо передать оба параметра следующим образом:

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

namespace classObjectMethodBasic
{
    public class Program
    {
        static void Main()
        {
            Console.WriteLine("Input a number for first number to do a math on: ");
            string input1 = Console.ReadLine();
            int number1 = 0;
            int.TryParse(input1, out number1);

            Console.WriteLine("Input a number for second number to do a math on or you need not enter one: ");
            string input2 = Console.ReadLine();
            int number2 = 0;
            int.TryParse(input2, out number2);

            int result1 = new int();
            result1 = Math.math(number1, number2);

            Console.WriteLine("Math result: " + result1);
            Console.ReadLine();
        }
    }
    public class Math
    {
        public static int math(int number1, int number2 = 3)
        {
            int result1 = number1 + number2;
            return result1;
        }
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...