samedi 4 mai 2019

C# Returning random string from list

I wrote out a list filled with answers for a question. I want to use my GetAnswer() method to return the current answer as a string. Also, I'm trying to keep the answer and never change it until Shake() is called.

Currently, I made a mistake somewhere because I'm getting errors. I think it is because I'm using var names in different methods that aren't available in other methods. In GetAnswer() it can't find the randomstring var

namespace Magic8Ball_Logic
{

public class Magic8Ball
{
    private List<string> _answers;
    private int _currentIndex;
    public Magic8Ball()
    {
        _answers = new List<string>();
        _answers.Add("It is certain.");
        _answers.Add("It is decidedly so.");
        _answers.Add("Without a doubt.");
    }

    public Magic8Ball(List<string> answers)
    {
        //I won't use the default. Use the ones passed in.
        _answers = answers;
    }

    public void Shake()
    {
        //picking the index of the answer to show the user
        Random r = new Random();
        int index = r.Next(_answers.Count);
        string randomString = _answers[index];
    }

    public string GetAnswer()
    {
        //using the index picked by shake to return the answer
        return "";
        return randomString;
    }




Aucun commentaire:

Enregistrer un commentaire