'Find and Resolve Cannot implicitly convert type 'string' to 'int' Error
Where am I getting this error and how does one resolve it?
namespace SimpleInterest
{
class Programsi
{
static void Main(string[]args)
{
Console.WriteLine("enter your age: ");
int age = Console.ReadLine();
Console.WriteLine("Deposit amount(P) Age Time Amount(SI) \n");
for(int y = 1; y <= 5; y++)
{
if(age>=60)
{
int SI = (23000*y*7)/100;
Console.WriteLine("23000.00 {0} {1} {2}",age, y, SI);
}
else
{
int SI = (23000*y*6)/100;
Console.WriteLine("23000.00 {0} {1} {2}",age, y, SI);
}
}
}
}
Solution 1:[1]
You are using int age = Console.ReadLine(); try to int as this ReadLine will read the complete line as string.
You can try below int age = Convert.ToInt32(Console.ReadLine());
Solution 2:[2]
As others pointed out, Console.ReadLine() returns a string. You need to manually convert it to an int. Here's an approach to do it safely:
Console.WriteLine("enter your age: ");
string input = Console.ReadLine(); // Change that to a string
if (!int.TryParse(input, out var age)) // Try to convert the input to an int
{
Console.WriteLine("Wrong input");
return;
}
Console.WriteLine("Deposit amount(P) Age Time Amount(SI) \n");
for(int y = 1; y <= 5; y++)
{
if(age>=60)
{
int SI = (23000*y*7)/100;
Console.WriteLine("23000.00 {0} {1} {2}",age, y, SI);
}
else
{
int SI = (23000*y*6)/100;
Console.WriteLine("23000.00 {0} {1} {2}",age, y, SI);
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Prashant Patel |
| Solution 2 | Arthur Rey |
