【问题标题】:C# Sorting - not all code paths return a valueC# 排序 - 并非所有代码路径都返回一个值
【发布时间】:2014-04-25 15:55:29
【问题描述】:

感谢所有答案,正如我之前所说,我是初学者,所以也许我会尝试从另一面展示我的问题。一开始我写了一个像下面这样的工作程序,但后来我意识到我的任务是使用那个密封的类,这对我来说太难了。

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

namespace Projekt_1__konsola
{
sealed class Element
{
    int val;
    public Element(int e)
    {
        val = e;
    }
    public int v
    {
        get
        {
            return val;
        }
    }
}

class Program
{
    static void UstawienieStylu()
    {
        Console.Title = "Projekt";
        Console.BackgroundColor = ConsoleColor.White;
        Console.ForegroundColor = ConsoleColor.Black;
        Console.Clear();
    }

    static void PodajLiczbę(string komunikat, out int liczba)
    {
        while (true)
        {
            Console.Write(komunikat);
            string str = Console.ReadLine();
            try
            {
                liczba = int.Parse(str);
                break;
            }
            catch (FormatException)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("Wprowadzono liczbę w złym formacie");
                Console.ForegroundColor = ConsoleColor.Black;
            }
            catch (OverflowException)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("Wartość jest za duża albo za mała");
                Console.ForegroundColor = ConsoleColor.Black;
            }
            catch (ArgumentNullException)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("Napotkano koniec strumienia");
                Console.ForegroundColor = ConsoleColor.Black;
            }
            Console.WriteLine("Spróbuj jeszcze raz");
        }
    }

    static void Sortuj(int[] tablica)
    {
        for (uint i = 1; i < tablica.Length; i++)
        {
            uint j = i;
            int buf = tablica[j];
            while ((j > 0) && (tablica[j - 1] > buf))
            {
                tablica[j] = tablica[j - 1];
                j--;
            }
            tablica[j] = buf;
        }
    }

    static void Main(string[] args)
    {
        UstawienieStylu();

        int liczba;
        PodajLiczbę("Podaj liczbę elementów do posortowania: ", out liczba);
        int element, i;
        int[] tablica = new int[liczba];
        for (i = 0; i < liczba; i++)
            {
                PodajLiczbę("Podaj element [" + i + "]: ", out element);
                tablica[i] = element;
            }

        Sortuj(tablica);

        Console.WriteLine("Posortowane elementy: ");
        for (i = 0; i < liczba; i++)
        {
            Console.WriteLine("Element [{0}] = {1}", i, tablica[i]);
        }
    }
}
}

我的任务是编写一个程序,该程序使用开头编写的确切类。没有它会很容易,但现在不是,因为我是编程初学者,尤其是对象。我做错了什么?

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

namespace Projekt_1__konsola
{
sealed class Element
{
    int val;
    public Element(int e)
    {
        val = e;
    }
    public int v
    {
        get
        {
            return val;
        }
    }
}

class Program
{
    static void UstawienieStylu()
    {
        Console.Title = "Projekt 1";
        Console.BackgroundColor = ConsoleColor.White;
        Console.ForegroundColor = ConsoleColor.Black;
        Console.Clear();
    }

    static Element[] WczytajDaneZKonsoli()
    {
        while (true)
        {
            string str = Console.ReadLine();
            int element;

            try
            {
                element = int.Parse(str);
                break;
            }
            catch (FormatException)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("Wprowadzono liczbę w złym formacie");
                Console.ForegroundColor = ConsoleColor.Black;
            }
            catch (OverflowException)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("Wartość jest za duża albo za mała, pamiętaj że możesz podać liczby z zakresu 1 do 4294967295");
                Console.ForegroundColor = ConsoleColor.Black;
            }
            catch (ArgumentNullException)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("Napotkano koniec strumienia");
                Console.ForegroundColor = ConsoleColor.Black;
            }
            Console.WriteLine("Spróbuj jeszcze raz");
        }
    }

    static void Sortowanie(Element[] tablica)
    {
        for (uint i = 1; i < tablica.Length; i++)
        {
            uint j = i;
            int buf = tablica[j].v;
            while ((j > 0) && (tablica[j - 1].v > buf))
            {
                tablica[j].e = tablica[j - 1].v;
                j--;
            }
            tablica[j].e = buf;
        }
    }

    static void WyświetlDane(Element[] elementy)
    {
        Console.WriteLine("Posortowane elementy: ");
        for (int i = 0; i < elementy.Length; i++)
        {
            Console.WriteLine("Element [{0}] = {1}", i, elementy[i].v);
        }
    }

    static void Main(string[] args)
    {
        UstawienieStylu();
        Element[] elementy = WczytajDaneZKonsoli();
        Sortowanie(elementy);
        WyświetlDane(elementy);
    }
}

}

【问题讨论】:

  • 顺便说一句,ArgumentNullException 并不意味着您的错误消息所说的那样

标签: c# methods


【解决方案1】:

您需要通过以下方法返回Element[]

static Element[] WczytajDaneZKonsoli()

注意:您的函数WczytajDaneZKonsoli() 似乎什么也没做,因此您需要创建一个Element[] 并返回它。

您可能需要添加以下代码来创建Element[] 数组,如下所示:

static Element[] WczytajDaneZKonsoli()
{
    Element [] myElements = new Element[10]; //size depends on your equirements

   //or you can use Lis<Element> if you don't know the size
    int count = 0;
    while (true)
    {
        string str = Console.ReadLine();
        int element;

        try
        {
            element = int.Parse(str);
            myElements[count]=new Element(element);
            count++;
            break;
        }

     return myElements;

【讨论】:

  • 这段代码永远不允许用户输入多个元素,这违背了这个程序的目的(排序元素)。
  • @KonradMorawski:为什么不超过一个元素,顺便说一句,您还应该考虑上面的代码只是描述了 OP 如何编写他的代码,它不是完整的实现
  • 因为你break在解析完第一个数字后退出了while循环。该方法只会返回用户输入的 1 个元素。 Element[1]Element[9] 将为空。
  • @KonradMorawski:是的,但是这个逻辑取决于 OP 想要如何执行,并且问题完全不同 not all code paths return a value 而且我没有破坏它只是他的代码......
【解决方案2】:

从函数返回一个Element[]

static Element[] WczytajDaneZKonsoli()

【讨论】:

    【解决方案3】:

    你的函数WczytajDaneZKonsoli 签名说它返回一个Element[] 但你没有返回任何东西。正如错误消息所说,该函数的所有代码路径都必须返回一个值(或因异常而终止)。

    另一种选择是更改签名,但您必须确保在您调用它的任何地方,它都不期望它返回任何内容。例如,在Program.Main()

    更改签名的示例。

    static void WczytajDaneZKonsoli()
    

    【讨论】:

    • 数组没有.Add 方法。您的代码绝不会允许用户输入多个元素。
    • 好的。我忘了补充一点,我的任务还说,表格的每个元素都应该是 Element 类的对象。而且我还有一个问题:在 Sortowanie 方法中,我尝试覆盖 val,但它是私有的,所以我不能并且这些行出现错误:tablica[j].**e** = tablica[j - 1] .v; tablica[j].**e** = buf;
    【解决方案4】:

    您的代码错误。

    您应该在 WczytajDaneZKonsoli 方法中填充元素集合(用户输入的数字),但现在您在用户输入的第一个数字之后打破了无限的 while 循环,所以他们无法输入超过 1 个的元素。

    显然,对由单个元素组成的数组进行排序是毫无意义的。

    其他建议的解决方案(目前)没有解决这个问题。

    您需要让您的用户决定他们是否已完成或仍想再添加一个号码。

    一旦你做对了,初始化Element 的集合(可能是List&lt;Element&gt;,因为你事先不知道会有多少元素)并继续向集合中添加更多元素。在用户确定没有更多数字后返回list.ToArray()

    工作解决方案:

        static Element[] WczytajDaneZKonsoli()
        {
            List<Element> elements = new List<Element>();
            Console.WriteLine("Keep on entering numbers, enter X once you're done");
            Console.WriteLine("Podawaj liczby. Wpisz X aby zakończyć i przejść do sortowania.");
            while (true)
            {                
                string str = Console.ReadLine();
                if (str == "X")
                {
                    break;
                }
    
                int element;
                try
                {
                    element = int.Parse(str);
                    elements.Add(new Element(element));
                }
                catch (FormatException)
                {
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine("Wprowadzono liczbę w złym formacie");
                    Console.ForegroundColor = ConsoleColor.Black;
                }
                catch (OverflowException)
                {
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine("Wartość jest za duża albo za mała, pamiętaj że możesz podać liczby z zakresu 1 do 4294967295");
                    Console.ForegroundColor = ConsoleColor.Black;
                }
                catch (ArgumentNullException)
                {
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine("Napotkano koniec strumienia");
                    Console.ForegroundColor = ConsoleColor.Black;
                }
                Console.WriteLine("Spróbuj jeszcze raz");
            }
            return elements.ToArray();
        }
    

    【讨论】:

      猜你喜欢
      • 2017-07-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-17
      • 1970-01-01
      相关资源
      最近更新 更多