Не все пути кода возвращают значение C# ошибка - PullRequest
0 голосов
/ 08 апреля 2020

В моем классе программирования C# мы выполняем упражнение, основанное на создании методов, и в моем методе я получаю ошибку «не все пути кода возвращают значение» в строке 26. Наши инструкции для этого были:

Создайте консольное приложение, которое вычисляет цену стола, и метод Main () которого вызывает четыре других метода: • Метод, позволяющий принимать количество ящиков на столе в качестве ввода с клавиатуры. Этот метод возвращает количество ящиков в метод Main (). • Метод приема и возврата типа древесины: «м» для красного дерева, «о» для дуба или «р» для сосны. • Метод, который принимает количество ящиков и тип дерева и рассчитывает стоимость стола на основании следующего: • Сосновые столы стоят 100 долларов. • Дубовые столы стоят 140 долларов. • Все остальные леса стоят 180 долларов. • За каждый ящик добавляется 30 долларов. • Этот метод возвращает стоимость методу Main (). • Метод для отображения всех деталей и окончательной цены. Сохраните файл как Desks.cs

Теперь я знаю, что у него нет 4 различных методов, как указано в требованиях, но я подумал, что могу его сократить.

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

namespace Desks.cs
{
    class Program
    {
        static void Main(string[] args)
        {
            int price = numDrawers() + woodType();
            Console.WriteLine("The total price is " + price);
            Console.ReadLine();
        }
        public static int numDrawers()
        {

            Console.Write("Enter the number of drawers you want with your desk: ");
            int drawers = Convert.ToInt32(Console.ReadLine());
            int drawerprice = 30 * drawers;
            Console.WriteLine("The number of drawers you want is " + drawerprice);
            return drawerprice;
        }
        public static int woodType()
        {
            char deskWood = 'a';
            while(deskWood != 'o' || deskWood != 'p' || deskWood != 'm')
            {
                Console.Write("Enter the type of wood you would like your desk to be made of \n Oak(o), Pine(p), or Mahogany(m): ");
                deskWood = Convert.ToChar(Console.ReadLine());
                int woodprice = 0;
                if (deskWood == 'o')
                {
                    woodprice += 140;
                    return woodprice;
                }
                else if (deskWood == 'p')
                {
                    woodprice += 100;
                    return woodprice;
                }
                else if (deskWood == 'm')
                {
                    woodprice += 180;
                    return woodprice;
                }
                else
                {
                    Console.WriteLine("There is no wood that corrisponds to that letter.");
                }
                Console.WriteLine("The type of wood you want the desk to be made of is " + deskWood);
            }
        }
    }

1 Ответ

0 голосов
/ 08 апреля 2020

Ошибка соответствует тому факту, что ваш метод woodType() не возвращает целое число на всех путях кода. Ваша программа будет выглядеть так:

using System;

public class Program
{
    public static void Main()
    {
        int getWoodTypePrice=woodType();
        if(getWoodTypePrice == 0)
        {
            Console.WriteLine("There is no wood that corrisponds to that letter.");
        }
        int price = numDrawers() + woodType();
        Console.WriteLine("The total price is " + price);
        Console.ReadLine();
    }

    public static int numDrawers()
    {

        Console.Write("Enter the number of drawers you want with your desk: ");
        int drawers = Convert.ToInt32(Console.ReadLine());
        int drawerprice = 30 * drawers;
        Console.WriteLine("The number of drawers you want is " + drawerprice);
        return drawerprice;
    }

    public static int woodType()
    {
        char deskWood = 'a';
        int woodprice = 0;
        while(deskWood != 'o' || deskWood != 'p' || deskWood != 'm')
        {
            Console.Write("Enter the type of wood you would like your desk to be made of \n Oak(o), Pine(p), or Mahogany(m): ");
            deskWood = Convert.ToChar(Console.ReadLine());

            if (deskWood == 'o')
            {
                woodprice += 140;
            }
            else if (deskWood == 'p')
            {
                woodprice += 100;
            }
            else if (deskWood == 'm')
            {
                woodprice += 180;                   
            }
            else
            {
                //Console.WriteLine("There is no wood that corrisponds to that letter.");
                return woodprice;
            }
            //Console.WriteLine("The type of wood you want the desk to be made of is " + deskWood);
        }
        return woodprice;
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...