简体   繁体   中英

How to assign a value read from the console to an integer field?

In my hangman game, I am attempting to prompt the user to enter the number of "lives" (or guesses) the player should be given. After I type a number at the prompt, the following error message is displayed:

Cannot implicitly convert type 'int' to 'string'

The following line causes the error:

lives = Console.ReadLine();

The lives field is an integer. How can I correctly assign a user-entered value to an integer field?

Here is my complete code:

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

namespace ConsoleApplication6
{
  class Hangman
  {
    //guesses
    public static int lives = 5;

    //Words for the game
    static string[] wordBank = { "study", "cat", "dress", "shoes", "lipstick" };
    // Create new ArrayList and initialize with words from array wordBank
    static ArrayList wordList = new ArrayList(wordBank);


    static void Main(string[] args)
    {
        Console.ForegroundColor = ConsoleColor.Green;
        Console.Title = "C# Hangman";
        Console.WriteLine("Hang man!");

        //Gamemenu
        string response = "";
        do
        {
            Console.Write("Enter Command (1. Add Words, 2. List Words , 3. Play , 4. Exit) Pick 1-4: ");
            response = Console.ReadLine();

            switch (response)
            {
                case "1": AddWord(); break;
                case "2": ListWords(); break;
                case "3": Play(); break;
                case "4": break;
            }
        } while (response != "4");
    }

    //add words to list
    static void AddWord()
    {
        Console.Write("Enter the word to add: ");
        String temp = Console.ReadLine();
        wordList.Add(temp);
        Console.WriteLine("{0} was added to the dictionary!", temp);
    }

    //Display words
    static void ListWords()
    {
        foreach (Object obj in wordList)
            Console.WriteLine("{0}", obj);
        Console.WriteLine();
    }


   //How many guesses
   static void AskLives()
   {
        try
        {
            Console.WriteLine("please enter number of lives?");

            //This line gives me the error
            lives = Console.ReadLine();
        }

        catch
        {
            // if user does not enter a number ask it again
            AskLives();
        }
    }

    //Gameplay
    static void Play()
    {
        Random random = new Random((int)DateTime.Now.Ticks);

        string wordToGuess = wordList[random.Next(0, wordList.Count)].ToString();
        string wordToGuessUppercase = wordToGuess.ToUpper();

        StringBuilder displayToPlayer = new StringBuilder(wordToGuess.Length);
        for (int i = 0; i < wordToGuess.Length; i++)
            displayToPlayer.Append('-');

        List<char> correctGuesses = new List<char>();
        List<char> incorrectGuesses = new List<char>();

        bool won = false;
        int lettersRevealed = 0;

        string input;
        char guess;

        AskLives();

        while (!won && lives > 0)
        {
            Console.WriteLine("Current word: " + displayToPlayer);
            Console.Write("Guess a letter: ");

            input = Console.ReadLine().ToUpper();
            guess = input[0];

            if (correctGuesses.Contains(guess))
            {
                Console.WriteLine("You've already tried '{0}', and it was correct!", guess);
                continue;
            }
            else if (incorrectGuesses.Contains(guess))
            {
                Console.WriteLine("You've already tried '{0}', and it was wrong!", guess);
                continue;
            }

            if (wordToGuessUppercase.Contains(guess))
            {
                correctGuesses.Add(guess);

                for (int i = 0; i < wordToGuess.Length; i++)
                {
                    if (wordToGuessUppercase[i] == guess)
                    {
                        displayToPlayer[i] = wordToGuess[i];
                        lettersRevealed++;
                    }
                }

                if (lettersRevealed == wordToGuess.Length)
                    won = true;
            }
            else
            {
                incorrectGuesses.Add(guess);

                Console.WriteLine("Nope, there's no '{0}' in it!", guess);
                lives--;
            }

            Console.WriteLine(displayToPlayer.ToString());
        }

        if (won)
            Console.WriteLine("You won!");
        else
            Console.WriteLine("You lost! It was '{0}'", wordToGuess);

        Console.Write("Press ENTER to exit...");
        Console.ReadLine();
        }
    }
}

Your lives field is an integer, but Console.ReadLine returns a string.

You can use Int32.Parse(Console.ReadLine()) to parse the input into an integer. Note that an exception will be thrown if the text entered by the user cannot be interpreted as an integer.

Your catch block will work here and re-prompt. It would be more appropriate to use the Int32.TryParse method:

int tmpLives;
if (Int32.TryParse(Console.ReadLine(), out tmpLives))
{
    lives = tmpLives;
}
else
{
    AskLives();
}

You want to do something along the lines of:

string livesString = Console.ReadLine();
lives = Convert.ToInt32(livesString);

I'm guessing Console.ReadLine() gives you a string. This will not play ball with your integer lives . You could try this:

lives = Int.Parse(Console.ReadLine())

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM