0

我不确定我问的是否正确,所以如果我犯了错误,请告诉我。

  1. 我已经尝试了几个小时的谷歌搜索和搜索堆栈,但没有找到我可以很好理解的结果来暗示(但我确实尝试过,老实说)。

  2. 我正在尝试制作一个辅助方法来插入我的代码中的几个不同位置。

这是方法

//Tried several methods (Do, Do While, For, et al) to make an insert code
    public Boolean insertFormat()//Method stub
    {
        Console.Clear(); //Clears out gunk, i hate gunk. I want to know I am looking at
        Console.WriteLine(title);//prints program title   
    }

我想我可以这样称呼它:

 while (true)
        {
            insertFormat;// This is where i'm trying to repeat the lines - i do this several times so i want to include them somehow (conditions vary) 

            Console.Clear(); //Clears out gunk, i hate gunk. I want to know I am looking at
            Console.WriteLine(title);//prints program title

            Console.WriteLine("For Breakfast may we suggest:" + bSelections[selectRandomArrayPosition(0, 4)] + "\n");
            Console.WriteLine("Please enter \"N\" for a new selection, or any other key to exit \n");
            suggestAgain = Console.ReadLine().ToLower();

            if (suggestAgain != "n") break;
        }

我已经尝试过 for loop、do、do while 等。试图作为一个变量做,但没有正确地做任何事情,所以它起作用了。一般来说,我最终得到一个错误说

'并非所有代码路径都返回一个值'。

我做了大约 6 次清除和重印标题,并且不想在我的程序中包含冗余代码,因为我被告知这不是一个好习惯。

4

2 回答 2

0

您的代码中有几个错误。这是工作版本。

public void insertFormat()
{
    Console.Clear();
    Console.WriteLine(title);
}

while (suggestAgain != "n")
{
    insertFormat();

    Console.WriteLine("For Breakfast may we suggest:" + bSelections[selectRandomArrayPosition(0, 4)] + "\n");
    Console.WriteLine("Please enter \"N\" for a new selection, or any other key to exit \n");

    suggestAgain = Console.ReadLine().ToLower();
}
于 2013-10-27T15:56:33.350 回答
0

从 insertFormat 方法中删除返回类型 (Boolean),因为您没有返回任何内容并且编译器会给出错误。将其更改为无效

public void insertFormat()//Method stub
{
    Console.Clear(); //Clears out gunk, i hate gunk. I want to know I am looking at
    Console.WriteLine(title);//prints program title   
}

// 调用代码

        while (true)
        {
            insertFormat();// This is where i'm trying to repeat the lines - i do this several times so i want to include them somehow (conditions vary) 

            // Skip them, insertFormat will execute them
            //Console.Clear(); //Clears out gunk, i hate gunk. I want to know I am looking at
            //Console.WriteLine(title);//prints program title

            Console.WriteLine("For Breakfast may we suggest:" + bSelections[selectRandomArrayPosition(0, 4)] + "\n");
            Console.WriteLine("Please enter \"N\" for a new selection, or any other key to exit \n");
            suggestAgain = Console.ReadLine().ToLower();

            if (suggestAgain != "n") break;
        }
于 2013-10-27T15:46:32.757 回答