繁体   English   中英

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

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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