在不同类的方法中打印数组?

发布于 2024-08-27 23:26:16 字数 3588 浏览 4 评论 0原文

我是一个相当缺乏经验的程序员,目前正在开发一个控制台应用程序项目。这基本上是一个小小的“数学游戏”;该应用程序生成两个随机数,这两个随机数可以随机相加、相减、相乘或相除。答案显示在屏幕上,用户必须从菜单中选择正确的数学运算符,一旦选择了正确的答案,应用程序就会在屏幕上显示用户输入正确答案所需的时间(以毫秒为单位)。

现在我想将玩家的时间保存在一个数组中,以后可以用所有分数来调用该数组。我需要在这个程序中包含一个方法,并且我认为一种将时间保存到数组中的方法是合适的。不过我似乎偶然发现了一个小问题。

我不太确定出了什么问题:

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

namespace Mathgame
{
    class Program
    {
    }

    class arrayclass
    {
        public static void saveInArray(int duration)
        {
            int[] TopTenScores = {000,1000,2000,3000,4000,5000,6000,7000,8000,9000};

            if (duration < 1000)
            {
                duration = TopTenScores[000];
            }
            else if ((duration >= 1000) && (duration <= 1999))
            {
                duration = TopTenScores[1000];
            }
            else if ((duration >= 2000) && (duration <= 2999))
            {
                duration = TopTenScores[2000];
            }
            else if ((duration >= 3000) && (duration <= 3999))
            {
                duration = TopTenScores[3000];
            }
            else if ((duration >= 4000) && (duration <= 4999))
            {
                duration = TopTenScores[4000];
            }
            else if ((duration >= 5000) && (duration <= 5999))
            {
                duration = TopTenScores[5000];
            }
            else if ((duration >= 6000) && (duration <= 6999))
            {
                duration = TopTenScores[6000];
            }
            else if ((duration >= 7000) && (duration <= 7999))
            {
                duration = TopTenScores[7000];
            }
            else if ((duration >= 8000) && (duration <= 8999))
            {
                duration = TopTenScores[8000];
            }
            else if ((duration >= 9000) && (duration <= 9999))
            {
                duration = TopTenScores[9000];
            }

            Console.WriteLine(TopTenScores);
        }

    static void Main(string[] args)
    {
        int intInput, num1, num2, incorrect, array1;
        float answer;
        string input;

        System.Random randNum = new System.Random();
        Console.WriteLine("Welcome to the Maths game!");
        Console.WriteLine("(Apologies for the glitchiness!)");
        Console.WriteLine();
        Console.WriteLine("Please choose from the following options:");
        Console.WriteLine();
    retry:
        Console.WriteLine("1 - Test your Maths against the clock!");
        Console.WriteLine("2 - Exit the application.");
        Console.WriteLine("3 - Top scores");
        Console.WriteLine();
        input = Console.ReadLine();
        intInput = int.Parse(input);

        if (intInput == 1)
        {
            goto start;
        }
        else if (intInput == 2)
        {
            goto fin;
        }
        else if (intInput == 3)
        {

            array1 = array1.saveInArray;

          goto retry;
        }

现在,在代码中的最后一个“else if”语句中,您可以看到我的变量 array1 尝试调用该方法,但无论我做什么,我都会不断收到错误。

这是我目前唯一的错误,但我有一种感觉,一旦解决该错误,另一个错误就会出现。现在我只是决心克服这个错误:

'int' does not contain a definition for 'saveInArray' and no extension method 'saveInArray' accepting a first argument of type 'int' could be found (are you missing a using directive or an assembly reference?).

任何帮助将不胜感激,为我丑陋的编写代码提前道歉!感谢您给我提供的任何帮助!

问候, 奥马尔.

I'm a fairly inexperienced programmer, and i'm currently working on a Console Application project. It's basically a little 'mathematics game'; the application generates two random numbers, that have either been added, subtracted, multiplied or divided against each other randomly. The answer is shown on screen and the user has to pick from the menu which is the right mathematical operator, once the correct answer is picked the application then displays on screen how long it took for the user in milliseconds to input the correct answer.

Now I want to save the times of the players in an array that can be called up later with all the scores. I need to include a method in this programme and I figured a method to save the times into an array would be suitable. I seem to have stumbled across a little problem though.

I'm not quite sure what's wrong:

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

namespace Mathgame
{
    class Program
    {
    }

    class arrayclass
    {
        public static void saveInArray(int duration)
        {
            int[] TopTenScores = {000,1000,2000,3000,4000,5000,6000,7000,8000,9000};

            if (duration < 1000)
            {
                duration = TopTenScores[000];
            }
            else if ((duration >= 1000) && (duration <= 1999))
            {
                duration = TopTenScores[1000];
            }
            else if ((duration >= 2000) && (duration <= 2999))
            {
                duration = TopTenScores[2000];
            }
            else if ((duration >= 3000) && (duration <= 3999))
            {
                duration = TopTenScores[3000];
            }
            else if ((duration >= 4000) && (duration <= 4999))
            {
                duration = TopTenScores[4000];
            }
            else if ((duration >= 5000) && (duration <= 5999))
            {
                duration = TopTenScores[5000];
            }
            else if ((duration >= 6000) && (duration <= 6999))
            {
                duration = TopTenScores[6000];
            }
            else if ((duration >= 7000) && (duration <= 7999))
            {
                duration = TopTenScores[7000];
            }
            else if ((duration >= 8000) && (duration <= 8999))
            {
                duration = TopTenScores[8000];
            }
            else if ((duration >= 9000) && (duration <= 9999))
            {
                duration = TopTenScores[9000];
            }

            Console.WriteLine(TopTenScores);
        }

    static void Main(string[] args)
    {
        int intInput, num1, num2, incorrect, array1;
        float answer;
        string input;

        System.Random randNum = new System.Random();
        Console.WriteLine("Welcome to the Maths game!");
        Console.WriteLine("(Apologies for the glitchiness!)");
        Console.WriteLine();
        Console.WriteLine("Please choose from the following options:");
        Console.WriteLine();
    retry:
        Console.WriteLine("1 - Test your Maths against the clock!");
        Console.WriteLine("2 - Exit the application.");
        Console.WriteLine("3 - Top scores");
        Console.WriteLine();
        input = Console.ReadLine();
        intInput = int.Parse(input);

        if (intInput == 1)
        {
            goto start;
        }
        else if (intInput == 2)
        {
            goto fin;
        }
        else if (intInput == 3)
        {

            array1 = array1.saveInArray;

          goto retry;
        }

Now, in the last 'else if' statement in the code, you can see my variable array1 trying to call the method, but no matter what I do I keep getting errors.

This is the only error I have at the moment, but I have a feeling soon as I resolve that error, another will come up. For now i'm just determined to get past this error:

'int' does not contain a definition for 'saveInArray' and no extension method 'saveInArray' accepting a first argument of type 'int' could be found (are you missing a using directive or an assembly reference?).

Any help would be kindly appreciated, apologies in advanced for my ugly written code! And thank you to any help that I receive!

Regards,
Omar.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

七颜 2024-09-03 23:26:16

好吧,

这段代码中有相当多的地方需要修复。

我首先从您的错误开始:

您将变量 array1 声明为整数。在 C# 中,整数是原始类型。这意味着它们没有方法,也没有类成员。因此,当您调用 array1.saveInArray 时,编译器基本上会说“整数类型没有任何方法......我找不到合适的方法来匹配您的调用”。

我认为您应该调用的是 arrayclass.saveInArray(x),而不是调用 array1.saveInArray(x)。

请注意上面调用中的 x。我将一个名为 x 的变量传递给函数 saveInArray(),该变量的类型为 int

这给我们带来了第二个错误。如果 saveInArray 是一个属性,那么您可以直接使用 arrayclass.saveInArray。然而,它是一个需要参数的函数……即整数。

当您调用 arrayclass.saveInArray(someInteger) 时,您将 someInteger 作为参数传递到方法中。然后该方法可以自由地使用该参数来进行计算。

这应该可以修复您最基本的错误,并希望您可以编译。

继续讨论一些会在运行时导致问题的其他错误:

在方法 saveInArray 中,您声明一个名为 TopTenScores 的整数数组。

您声明这很好...但是稍后当您对 TopTenScores 建立索引时,您使用的索引远远超出了 TopTenScores 的范围。

以下是您的 TopTenScores 声明:

int[] TopTenScores = {000,1000,2000,3000,4000,5000,6000,7000,8000,9000};

请注意,此声明中有 10 个数字。这意味着您可以拥有的最大索引是9。为什么?因为在 C# 中数组从 0 开始索引。

我想您可能会认为这个数组是关联的......但事实并非如此。当您执行 TopTenScores[1000] 时,您是在说“给我索引 1000 处的值”。该值不存在,您将收到运行时错误。

相反,如果您想访问值 1000,则需要调用 TopTenScores[1]

此外,您不会用新的最高分数覆盖默认值,而是覆盖新的最高分数使用默认值。我认为这不是故意的。相反,请将您的通话从:duration = TopTenScores[1000];切换

为:TopTenScores[1] =uration;

编辑:最后,正如评论者指出的那样,使用 goto 是一种不好的做法,并且非常不鼓励。当您稍后开始更好地理解程序流程和组织时,您就会明白其中的原因。目前,最好尝试避免使用 goto 的习惯。 goto 映射到低级系统构造,在使用 C# 等高级语言时我们应该避免这种情况。使用 goto 会使您的代码很快变得混乱且容易出错。

无论如何,如果您有疑问或需要澄清某些内容,请随时提出更多问题/评论等。欢迎来到 StackOverflow!

Okay,

There's quite a bit in this code that needs fixing TBH.

I'll start with your error first:

You are declaring the variable array1 as an integer. In C# integers are primitive types. This means that they have no methods and no class members. So, when you call array1.saveInArray the compiler is basically saying "the type integer doesn't have any methods... I can't find an appropriate method to match your call".

Instead of calling array1.saveInArray I think what you meant to call was arrayclass.saveInArray(x).

Notice the x in that call above. I'm passing a variable called x which is of type int into the function saveInArray().

This brings us to the second error. If saveInArray was a property, then you could just go arrayclass.saveInArray. However, it is a function which requires an argument... namely an integer.

When you call arrayclass.saveInArray(someInteger) you are passing someInteger as an argument into a method. The method is then free to use this argument to do its calculations.

That should fix your most basic errors and hopefully you can compile.

Moving on to some other errors that will cause you problems at runtime:

In the method saveInArray you are declaring an integer array called TopTenScores.

You are declaring this fine... however later on when you are indexing into TopTenScores, you are using an index that is way out of range of TopTenScores.

Here is your declaration of TopTenScores:

int[] TopTenScores = {000,1000,2000,3000,4000,5000,6000,7000,8000,9000};

Notice that there are 10 numbers in this declaration. This means that the max index you can have is 9. Why? Because arrays start indexing at 0 in C#.

I think you might be thinking that this array is associative... however this is not the case. When you do TopTenScores[1000] you are saying "give me the value at index 1000". This value does not exists and you will get a runtime error.

Instead, you would want to call TopTenScores[1] if you wanted to access the value 1000.

Also, you are not overwriting the default value with the new top score, rather you are overwriting the new top score with the default value. I don't think this is intended. Instead, switch your calls from this: duration = TopTenScores[1000];

to this: TopTenScores[1] = duration;

Edit: Lastly, as the commenter pointed out, using goto is bad practice and greatly discouraged. You will understand why later on as you start to understand program flow and organization better. For now, it is best to try and avoid the habit of using goto. goto maps to a low level system construct, which we should avoid when using a higher level language like C#. Your code can get confusing and error prone quickly with using goto.

Anyways, feel free to ask more questions/comment etc if you have questions or you need to clarify something. Welcome to StackOverflow!

墨小墨 2024-09-03 23:26:16

您的问题之一是您缺少数组的基本概念。将数组视为一排编号的邮箱。这行代码:

int[] TopTenScores = {000,1000,2000,3000,4000,5000,6000,7000,8000,9000};

正在创建一个由 10 个整数组成的数组,在内存中看起来像这样:

  Index  Value
  -----  -----
  0          0
  1       1000
  2       2000
  3       3000
  4       4000
  5       5000
  6       6000
  7       7000
  8       8000
  9       9000

目前尚不清楚这是一个表示您最高分数的有用结构,而且我不确定您的 saveInArray 方法正在尝试做。在该方法中,其中一行代码的解释方式如下:

duration = TopTenScores[1000];

这意味着“获取 TopTenScores 索引 1000 处的内容并将其存储在 duration 中。”从上表中可以看出,没有索引 1000,而且该代码与保存最高分无关。

您遇到的另一个问题是您似乎没有适当的算法来完成任务。对于前十项功能,请尝试将需要完成的操作分解为说明,说明如果您是记分员,您将如何手动执行此操作。事情大概是这样的:

  • 我通过按照从高到低的顺序堆叠索引卡来跟踪最高分。起初,我没有索引卡。
  • 我可以做两件事:记录分数并告诉别人前十名的分数。
  • 当有人要求我记录分数时,我:
    1. 将分数写在索引卡上
    2. 按顺序查看之前的分数堆栈,直到找到低于此新分数的分数。
    3. 如果我发现一个分数低于新分数,我会将卡片放在较低分数的上面。
    4. 否则,如果此分数是所有分数中最低的分数(包括这是记录的第一个分数),我会将分数放在堆栈的底部。
  • 当有人让我告诉他们前 10 名的分数时,我:
    1. 翻阅前 10 张卡片,如果我的卡片少于 10 张,则翻阅所有卡片。
    2. 将每个分数按顺序写下来。
    3. 将分数列表提供给请求者。

这样做可能看起来很愚蠢,但大多数程序实际上只是简单步骤的序列,作为程序员,您需要能够确定这些步骤,然后才能将它们翻译成编译器可以理解的语言。一旦你用简单的术语表达了问题,你就可以开始将其翻译成代码,例如:

// You can think of a role a person would do for a manual process as a class
// in a program.
public class ScoreKeeper
{
    // Our high score list (stack of cards) is empty to begin with.  Unlike
    // arrays, lists allow us insert items rather than placing them in 
    // numbered slots.
    private List<int> _scores = new List<int>();

    // This is the method for when someone asks us to record a score.  The
    // "score" parameter is the new score which you can think of as being 
    // written on a card.
    public void RecordScore(int score)
    {
        // Go through each of the existing scores.  "i" is the index in the
        // list.
        for (int i = 0; i < _scores.Count; i++)
        {
            // See if the new score is less than the score at index #i
            if (_scores[i] < score)
            {
                // It is lower than this new score.  Insert the new score
                // above that score.
                _scores.Insert(i, score);

                // We're done.  Stop looping and exit RecordScore.
                return;
            }
        }

        // If we get here, we found no scores lower than this new one.  Add 
        // this score to the bottom of the stack.
        _scores.Add(score);
    }

    // This is the method for when someone asks us for the top 10 scores.
    // Notice that we return an array of integers, which will represent 
    // our piece of paper we hand back to the one requesting the scores.
    public int[] GetTop10Scores()
    {
        // We start with a blank piece of paper.
        int[] result = new int[10];

        // Go through the scores.  The first 10 are the top 10 because
        // RecordScore puts them in order.  We also need to make sure
        // we don't try to get more scores than we've recorded.
        for (int i = 0; i < 10 && i < _scores.Count; i++)
        {
            // Write down the score on the paper
            result[i] = _scores[i];
        }

        // Send back the list of scores to the requester
        return result;
    }
}

现在,在你的主程序中,你可以创建一个 ScoreKeeper 并要求它进行记分:

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("Welcome to the Maths game!");
        Console.WriteLine("(Apologies for the glitchiness!)");
        Console.WriteLine();
        Console.WriteLine("Please choose from the following options:");
        Console.WriteLine();

        // This object keeps track of scores
        ScoreKeeper scoreKeeper = new ScoreKeeper();

        bool keepRunning = true;
        while (keepRunning)
        {
            Console.WriteLine("1 - Test your Maths against the clock!");
            Console.WriteLine("2 - Exit the application.");
            Console.WriteLine("3 - Top scores");
            Console.WriteLine();
            string input = Console.ReadLine();
            int intInput = int.Parse(input);

            if (intInput == 1)
            {
                // You should avoid gotos.  Try writing a method instead

                // Play the game and get the player's score.
                int newScore = PlayGame();

                // Have the score keeper record the new score.
                scoreKeeper.RecordScore(newScore);
            }
            else if (intInput == 2)
            {
                keepRunning = false;
            }
            else if (intInput == 3)
            {
                // Get the top scores from the score keeper
                int[] topScores = scoreKeeper.GetTop10Scores();

                // Print each score
                for (int i = 0; i < topScores.Length; i++)
                {
                    Console.WriteLine("{0}: {1}", i + 1, topScores[i]);
                }
            }
        }
    }

    private static int PlayGame()
    {
        // Put your game logic in here.  Return the score.
    }
}

一旦你更加熟悉了编程时,您会发现可以重用现有的类,例如 SortedList,它已经可以处理常见任务,例如维护有序列表。

One of your problems is that you're missing the fundamental concept of what an array is. Think of an array as a row of numbered mailboxes. This line of code:

int[] TopTenScores = {000,1000,2000,3000,4000,5000,6000,7000,8000,9000};

is creating an array of 10 integers that look something like this in memory:

  Index  Value
  -----  -----
  0          0
  1       1000
  2       2000
  3       3000
  4       4000
  5       5000
  6       6000
  7       7000
  8       8000
  9       9000

It is unclear how this is a useful structure to represent your top scores, and I'm not sure what your saveInArray method is trying to do. In that method, here's how one of your lines of code is interpreted:

duration = TopTenScores[1000];

What that means is "take what's at index 1000 of TopTenScores and store it in duration." As you can see from the table above, there is no index 1000, and besides, that code has nothing to do with saving a top score.

Another problem you're having is that you don't seem to have your algorithm in place for accomplishing the task. For the top ten functionality, try breaking down what needs to be done into instructions on how you would do it manually if you were a score keeper. It would be something like this:

  • I keep track of the top scores by stacking index cards with the scores on them in order of highest to lowest. At first, I have no index cards.
  • I can do two things: record scores and tell someone the top ten scores.
  • When someone asks me to record a score, I:
    1. Write the score down on an index card
    2. Look through the stack of previous scores in order until I find a score lower than this new score.
    3. If I find a score that was lower than this new one, I place the card on top of the lower score.
    4. Otherwise, if this score is the lowest one of the bunch, including if this is the first score recorded, I'll place the score at the bottom of the stack.
  • When someone asks me to tell them the top 10 scores, I:
    1. Go through the first 10 cards or all the cards if I have less than 10.
    2. For each of those scores, write them down in order.
    3. Give the list of scores to the one requesting them.

It may seem silly to do this, but most programs are really only sequences of simple steps, and as a programmer, you need to be able to determine those steps before translating them into a language that the compiler can understand. Once you formulate the problem in simple terms, you can start translating it into code for example:

// You can think of a role a person would do for a manual process as a class
// in a program.
public class ScoreKeeper
{
    // Our high score list (stack of cards) is empty to begin with.  Unlike
    // arrays, lists allow us insert items rather than placing them in 
    // numbered slots.
    private List<int> _scores = new List<int>();

    // This is the method for when someone asks us to record a score.  The
    // "score" parameter is the new score which you can think of as being 
    // written on a card.
    public void RecordScore(int score)
    {
        // Go through each of the existing scores.  "i" is the index in the
        // list.
        for (int i = 0; i < _scores.Count; i++)
        {
            // See if the new score is less than the score at index #i
            if (_scores[i] < score)
            {
                // It is lower than this new score.  Insert the new score
                // above that score.
                _scores.Insert(i, score);

                // We're done.  Stop looping and exit RecordScore.
                return;
            }
        }

        // If we get here, we found no scores lower than this new one.  Add 
        // this score to the bottom of the stack.
        _scores.Add(score);
    }

    // This is the method for when someone asks us for the top 10 scores.
    // Notice that we return an array of integers, which will represent 
    // our piece of paper we hand back to the one requesting the scores.
    public int[] GetTop10Scores()
    {
        // We start with a blank piece of paper.
        int[] result = new int[10];

        // Go through the scores.  The first 10 are the top 10 because
        // RecordScore puts them in order.  We also need to make sure
        // we don't try to get more scores than we've recorded.
        for (int i = 0; i < 10 && i < _scores.Count; i++)
        {
            // Write down the score on the paper
            result[i] = _scores[i];
        }

        // Send back the list of scores to the requester
        return result;
    }
}

Now, inside of your main program, you can create a ScoreKeeper and ask it to do its score keeping:

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("Welcome to the Maths game!");
        Console.WriteLine("(Apologies for the glitchiness!)");
        Console.WriteLine();
        Console.WriteLine("Please choose from the following options:");
        Console.WriteLine();

        // This object keeps track of scores
        ScoreKeeper scoreKeeper = new ScoreKeeper();

        bool keepRunning = true;
        while (keepRunning)
        {
            Console.WriteLine("1 - Test your Maths against the clock!");
            Console.WriteLine("2 - Exit the application.");
            Console.WriteLine("3 - Top scores");
            Console.WriteLine();
            string input = Console.ReadLine();
            int intInput = int.Parse(input);

            if (intInput == 1)
            {
                // You should avoid gotos.  Try writing a method instead

                // Play the game and get the player's score.
                int newScore = PlayGame();

                // Have the score keeper record the new score.
                scoreKeeper.RecordScore(newScore);
            }
            else if (intInput == 2)
            {
                keepRunning = false;
            }
            else if (intInput == 3)
            {
                // Get the top scores from the score keeper
                int[] topScores = scoreKeeper.GetTop10Scores();

                // Print each score
                for (int i = 0; i < topScores.Length; i++)
                {
                    Console.WriteLine("{0}: {1}", i + 1, topScores[i]);
                }
            }
        }
    }

    private static int PlayGame()
    {
        // Put your game logic in here.  Return the score.
    }
}

Once you become more familiar with the fundamentals of programming, you'll find there are existing classes you can reuse, like SortedList, that can already take care of common tasks like maintaining an ordered list.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文