【问题标题】:cannot convert int to string simple age program无法将 int 转换为字符串简单的年龄程序
【发布时间】:2019-11-06 21:45:58
【问题描述】:

我的程序有一个奇怪的问题。我想打印出我的名字、姓氏和年龄,我觉得这里有一个我只是没有看到的简单解决方案。

这是我的代码:

string firstname; //the data type that is named and initialised 
string lastname;
string userAge;
int age;

//takes user input 
Console.Write("please enter your first name - "); 

//stores user input 
firstname = Console.ReadLine(); 

Console.Write("please enter your last name - ");

lastname = Console.ReadLine();

Console.Write("please enter your age - ");

userAge = Console.ReadLine();

//this is a bit of useless code I was playing around with earlier     
//age = Console.Readline();              

userAge = Convert.ToInt32(age);

//prints user input to screen the 0 is the position
Console.WriteLine("Your name is {0} {1}", firstname,lastname + "and your age is",age); 

//pauses the program for 1000 mlseconds so you can see what the result is 
Thread.Sleep(2000); 

【问题讨论】:

  • 你能解释一下它的哪一部分不起作用吗?你看到了什么?你能指望什么?这对于有经验的开发人员来说可能很明显,但在编写高质量问题时它们是重要的细节。
  • 对不起 userAge = convvert.ToInt32(age);有一个错误说你不能简单地将类型 int 转换为字符串我想在屏幕上打印我的名字姓氏和年龄年龄部分不起作用,因为它不显示数字

标签: c# string int


【解决方案1】:

它给你这个错误是因为ToInt32string 作为输入,而你给它一个int。相反,您应该给它string,然后得到int

userAge = Console.ReadLine();            
age = Convert.ToInt32(userAge);

但实际上,您不需要转换任何内容。相反,将所有内容都保留为字符串。另外,您对WriteLine 的使用有点错误:

string firstname;
string lastname;
string userAge;

//takes user input 
Console.Write("please enter your first name - "); 

//stores user input 
firstname = Console.ReadLine(); 

Console.Write("please enter your last name - ");

lastname = Console.ReadLine();

Console.Write("please enter your age - ");

userAge = Console.ReadLine();  

//prints user input to screen the 0 is the position
Console.WriteLine("Your name is {0} {1} and your age is {2}.", 
        firstname, lastname, userAge); 

//pauses the program for 1000 mlseconds so you can see what the result is 
Thread.Sleep(2000); 

【讨论】:

  • 如果我想将年龄保持为整数,我该怎么做
【解决方案2】:

你应该使用:

age = Convert.ToInt32(userAge);

还有:

Console.WriteLine($"Your name is {firstname} {lastname} and your age is {age}"); 

$ 允许字符串插值将变量放在字符串中的 {} 之间。

如果在 uint 上输入了非数字或不能放入 int 中,您可以使用 TryParse 而不是 Convert 引发异常,因为 age 必须为正数:

uint age;  // instead of int
uint.TryParse(userAge, out age);

所以如果出现错误,年龄为 0。

你也可以测试这个方法的结果是否为假,以防出错,进行操作,例如:

do 
{ 
  Console.Write("please enter your age - ");
  userAge = Console.ReadLine();
}
while ( !uint.TryParse(userAge, out age) )

【讨论】:

    猜你喜欢
    • 2013-09-16
    • 1970-01-01
    • 2018-05-10
    • 2017-06-09
    • 1970-01-01
    • 2020-12-12
    • 1970-01-01
    • 1970-01-01
    • 2014-12-22
    相关资源
    最近更新 更多