c# -获取年龄的用户输入.但是接收错误

本文关键字:错误 输入 用户 获取 | 更新日期: 2023-09-27 18:09:18

我正在努力改进我的编程,让事情钻进我的头脑,所以我只是快速开发一个应用程序,获取用户的输入并打印他们的名字。但也得到了他们输入的"年龄验证"。

我正在练习IF &ELSE语句和嵌套类。

然而,我的编译器给了我一个错误,我似乎无法弄清楚。我试图让用户输入他的年龄,然后继续使用IF &ELSE语句。

编译器正在射击错误。不能隐式转换类型String to int"

现在程序中唯一的错误是myCharacter。age = Console.ReadLine();

using System;
namespace csharptut
{
    class CharPrintName
    {
        static void Main()
        {
            Character myCharacter = new Character();
            Console.WriteLine("Please enter your name to continue: ");
            myCharacter.name = Console.ReadLine();
            Console.WriteLine("Hello {0}!", myCharacter.name);
            Console.WriteLine("Please enter your age for verification purposes: ");
            myCharacter.age = Console.ReadLine();
            if (myCharacter.age <= 17)
            {
Console.WriteLine("I'm sorry {0}, you're too young to enter!",myCharacter.name);
            }
            else if (myCharacter.age >= 18)
            {
                Console.WriteLine("You can enter!");
            }
        }
    }
    class Character
    {
        public string name;
        public int age;
    }
}

c# -获取年龄的用户输入.但是接收错误

错误提示不能隐式地将字符串类型转换为int类型。您需要将其解析为int类型。

 string input = Console.ReadLine();
 int age;
 if (int.TryParse(input, out age)
 {
     // input is an int
     myCharacter.age = age;
 }
 else
 {
     // input is not an int
 }

您正在尝试将字符串值赋给int类型,如:

myCharacter.age = Console.ReadLine();

试题:

myCharacter.age = Int32.Parse(Console.ReadLine());

字符。age期望一个Int,但是ReadLine()返回一个字符串,你需要使用int.Parseint.TryParse来避免异常

  if (!int.TryParse(Console.ReadLine(),out myCharacter.age)) {
    Console.WriteLine("You didn't enter a number!!!");
  } else if (myCharacter.age <= 17) { 
    Console.WriteLine("I'm sorry {0}, you're too young to enter!",myCharacter.name); 
  }  else { 
    Console.WriteLine("You can enter!"); 
  } 

这看起来像一个学生项目。

来自ReadLine()的输入总是字符串类型。然后将字符串与17进行比较,这是无效的,因为17是int型。使用TryParse和parse来避免在运行时抛出异常。

string typedAge = Console.ReadLine();
int Age = 0;
if (!int.TryParse(typedAge, out Age))
  Console.WriteLine("Invalid age");
if (Age <= 17)
  Console.WriteLine("You're awfully young.");

OK。这里的问题是年龄被定义为int,而Console.ReadLine()总是返回字符串,因此您必须将用户输入从字符串转换为整数才能正确存储年龄。像这样:

myCharacter.age = Int32.Parse(Console.ReadLine());

当您从控制台读取输入时,它将以字符串的形式返回给您。c#是一种静态类型语言,您不能简单地将一种类型应用于另一种类型。你需要转换它,有几种方法可以做到这一点。

第一种方法是:

myCharacter.age = (int)Console.ReadLine();

这不起作用,因为字符串和整数是两种完全不同的类型,不能简单地将一种类型转换为另一种类型。请阅读有关类型转换的更多信息。

第二种方法是转换它,同样有两种方法:

myCharacter.age = Int32.Parse(Console.ReadLine());

只要您键入一个实际的数字,这将工作,在这种情况下,Parse方法读取字符串并找出适合您的整数是什么。然而,如果您输入"ABC",您将得到一个异常,因为Parse方法不将其识别为整数。所以更好的方法是:

string newAge = Console.ReadLine();
int theAge;
bool success = Int32.TryParse(newAge, out theAge);
if(!success)
   Console.WriteLine("Hey! That's not a number!");
else
   myCharacter.age = theAge;

在这种情况下,TryParse方法试图解析它,而不是抛出一个异常,它告诉你它不能解析它(通过返回值),并允许你直接处理(而不是通过try/catch)。

这有点啰嗦,但是你说你在学习,所以我想我应该给你一些东西来考虑和阅读。