Как вернуть значение в массив

Я делаю простой опрос / опрос, чтобы проверить, куда пользователь может пойти на работу. Я пошел с ответами да или нет. Я сделал счетчик баллов, чтобы он мог проверить информацию пользователя, если он ответил "да", а затем добавить одно очко. Я хочу создать функцию, которая отображает вопрос и проверяет пользовательский ввод вместо того, чтобы писать один и тот же цикл do while для каждого вопроса. Я сделал массив для сбора "пользовательских баллов". Но проблема в том, что, поскольку программа переходит в цикл и добавляет +1 точку, она просто не может вернуть значение этому "массиву точек". Это значение находится где-то еще в памяти, но не в массиве. Это приводит к неправильной работе резюме. Он просто показывает везде 0 баллов за каждую возможную работу. Что я сделал не так или что я могу сделать, чтобы он работал правильно?

Вот мой код (я, вероятно, испортил фигурные скобки копированием / вставкой):

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

namespace Survey
{
    class Program
    {
        static void Main(string[] args)
        {
        //here's my Question Bank

        ArrayList QuestionList = new ArrayList();
        QuestionList.Add("1. Question");
        QuestionList.Add("2. ...");
        QuestionList.Add("3. ...");
        QuestionList.Add("4. ...");
        QuestionList.Add("5. ...");
        QuestionList.Add("6. ...");
        QuestionList.Add("7. ...");
        QuestionList.Add("8. ...");
        QuestionList.Add("9. ...");
        QuestionList.Add("10. ...");

        //here's my work list.
        ArrayList WorkList = new ArrayList();
        WorkList.Add("IT");
        WorkList.Add("Architect");
        WorkList.Add("Politician");
        WorkList.Add("Driver");
        WorkList.Add("Designer");

        //here's an array, where I want to hold "points". The higher points the more probably user will get suggestion where to work.
        int[] Work;
        Work = new int[5] { 0, 0, 0, 0, 0 };

        Console.WriteLine("Hi. Say 'y' if you agree or 'n' if not.");

        displayQuestion(QuestionList[0], Work[0]);
        displayQuestion(QuestionList[1], Work[1]);
        displayQuestion(QuestionList[2], Work[2]);
        displayQuestion(QuestionList[3], Work[3]);
        displayQuestion(QuestionList[4], Work[4]);
        displayQuestion(QuestionList[5], Work[4]);
        displayQuestion(QuestionList[6], Work[1]);
        displayQuestion(QuestionList[7], Work[2]);
        displayQuestion(QuestionList[8], Work[0]);
        displayQuestion(QuestionList[9], Work[3]);

        // here's calculating maximum points 
        int max;
        max = Work[0];
        for (int i=0; i<5; i++)
        {
            if (Work[i] > max)
                max = Work[i];
        }

        for (int i = 0; i < 5; i++)
        {
            if(Work[i]==max)
            Console.WriteLine("You can work as: " + WorkList[i]);
        }

        //Summary
        Console.WriteLine("Points as: " + WorkList[0] + " = " + Work[0]);
        Console.WriteLine("Points as: " + WorkList[1] + " = " + Work[1]);
        Console.WriteLine("Points as: " + WorkList[2] + " = " + Work[2]);
        Console.WriteLine("Points as: " + WorkList[3] + " = " + Work[3]);
        Console.WriteLine("Points as: " + WorkList[4] + " = " + Work[4]);

        Console.ReadLine();

    }

    //here's the PROBLEM (I think)
    public static int displayQuestion(object whichQuestion, int WorkPoints)
    {
        string answer;

        do
        {
            Console.WriteLine(whichQuestion);
            answer = Console.ReadLine();
            if (answer == "y")
            {
                WorkPoints++;
            }
        } while (answer != "y" && answer != "y");
        return WorkPoints;
        }
    }
}

2 ответа

Решение

Фактически вы назначаете новый счет возвращаемому значению метода displayQuestion и не используете его.

public static int displayQuestion(object whichQuestion, int WorkPoints)

так что возможный подход - это использование the ключевое слово ref, как сказал Самвел, или назначьте возвращаемое значение метода для работы [i]:

Work[0] = displayQuestion(QuestionList[0], Work[0]);

Измените функцию на следующую:

public static int displayQuestion(object whichQuestion)
{
    string answer;
    int WorkPoints = 0;
    do
    {
        Console.WriteLine(whichQuestion);
        answer = Console.ReadLine();
        if (answer == "y")
        {
            WorkPoints++;
        }
    } while (answer != "y" && answer != "n");
    return WorkPoints;
    }
}

и затем используйте это так:

Work[0] += displayQuestion(QuestionList[0]);
Другие вопросы по тегам