如何将从控制台读取的值分配给整数字段

本文关键字:分配 整数 数字段 读取 控制台 | 更新日期: 2024-10-21 00:17:25

在我的刽子手游戏中,我试图提示用户输入玩家应该获得的"生命"数(或猜测)。在提示符处键入数字后,将显示以下错误消息:

Cannot implicitly convert type 'int' to 'string'

以下行导致错误:

lives = Console.ReadLine();

lives字段是一个整数。如何将用户输入的值正确分配给整数字段?

这是我的完整代码:

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();
        }
    }
}

如何将从控制台读取的值分配给整数字段

您的lives字段是一个整数,但Console.ReadLine返回一个字符串。

您可以使用Int32.Parse(Console.ReadLine())将输入解析为整数。请注意,如果用户输入的文本不能解释为整数,则会引发异常。

您的catch块将在此处工作并重新提示。使用Int32.TryParse方法更合适:

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

您想要按照以下步骤来做一些事情:

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

我猜Console.ReadLine()会给你一个字符串。这不会和你的整数lives一起打球。你可以试试这个:

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