Cannot implicitly convert string to int - c#

I'm trying to make a little multiplication only calculator.
I'm trying to do
int a;
a = Console.ReadLine();
and then it tell me cannot implicitly convert string to int.
I'd like it to readline my int variable and multiply it together with another int variable but its not letting me.
Thank you
namespace ConsoleApp9
{
class Program
{
static void Main(string[] args)
{
int a;
int b;
Console.WriteLine("Hey I'm a calculator in training and I'd like to test out my skills with you.");
Console.WriteLine("I can only do one type of equation right now but I'm still learning");
Console.WriteLine("What will your first number be?");
a = Console.ReadLine();
Console.WriteLine("So youre first number is ");
Console.Write(a);
Console.WriteLine(" Alrighty then what is your second number ?");
b = Console.ReadLine();
Console.WriteLine(a);
Console.WriteLine("*");
Console.WriteLine(b);
Console.WriteLine("=");
Console.WriteLine(a * b);
}
}
}

Method
Console.ReadLine();
actually returns string. Whereas variable of type int only stores integers not string representation of integers. So you need to convert your input from string to int. Since there is no implicit conversion from string to int, so you need to convert explicitly. You can do this like this
int a = Convert.ToInt32(Console.ReadLine()); OR
int a = int.Parse(Console.ReadLine()); OR
int a = (int) Console.ReadLine();
There are other ways as well. For details visit How to: Convert a String to a Number (C# Programming Guide)

Related

C# My code is not doing math.. it is just sticking the numbers together

I am creating a friendly ai whose name is Phil ;), but I need it to be able to do math. I did try, and I also tried +=, but it wont work. For example, if I did 1+1, instead of 2, it would give me 11. Here is my code:
namespace Game
{
public static class Program
{
//commands
public static string enteredCommand;
public static string commanddomath = "doMath";
//Math command stuff
public static string MathOperation;
public static string FirstOperatorNumber;
public static string SecondOperatorNumber;
public static string FinalAwnser;
static void Main()
{
if (enteredCommand == "doMath")
{
Console.WriteLine("Ok");
Console.WriteLine("What Operation should I do?");
MathOperation = Console.ReadLine();
if (MathOperation == "+")
{
Console.WriteLine("Addition! Easy! What is the first number? ex. 6");
FirstOperatorNumber = Console.ReadLine();
Console.WriteLine("Ok, what do you want the second number to be? ex. 8");
SecondOperatorNumber = Console.ReadLine();
FinalAwnser = FirstOperatorNumber + SecondOperatorNumber;
Console.WriteLine("Ok! The awnser is..." + FinalAwnser);
}
}
else
{
Console.WriteLine("That is not a command");
}
Console.ReadKey();
}
}
}
Any help is appreciated!
Thanks
You are storing the user's input (FirstOperatorNumber and SecondOperatorNumber) as strings. The addition operator (+), when applied to two strings, performs an operation called concatenation: it adds the characters from each string to form another string.
But you want addition, which is the result of the addition operator being used on two integers. So you must store the user's input as an integer by replacing 'string' with 'int' in the variable declaration:
public static int FirstOperatorNumber;
public static int SecondOperatorNumber;
The input will still be a string, so you need to convert it as well, like this:
FirstOperatorNumber = Int32.Parse(Console.ReadLine());

I have a problem converting int to double

I'm a beginner programmer and at this moment i try to create primitive program for define variable types.
Below code and core of my problem.
namespace Moving
{
internal class Program
{
static void Main(string[] args)
{
string input = Console.ReadLine();
if (int.TryParse(input, out int result1))
{
Console.WriteLine("type int");
}
if (double.TryParse(input, out double result2))
{
Console.WriteLine("type double");
}
else
{
Console.WriteLine("type String");
}
Console.ReadLine();
}
}
}
When i use string or double it works normally. But when i input int, works first if{} and second if{} too. For example i input 12. Program writes "type int" and "type double" because int may convert to double without efforts. I don't need it. Can i don't convert variable int to double? And i haven't a clue how i can explain to program to see difference between "string" and "char". What may do with it?
Because (mathematically) 1 = 1.0 is true, knowing this we derive that all integers are also valid decimal numbers, in programming terms we call them floating point numbers, and double is a floating point number type, meaning, it represents a floating point number, and as such can also represent integers*. So technically there's no problem, but it's not behaving how we want it to behave, so how do we fix this?
Easy, we use an else if statement instead of an if statement. The else if is only checked if the if (or else if) before it is false. Implementing it looks like this:
string input = Console.ReadLine();
if (int.TryParse(input, out int intResult))
{
Console.WriteLine("Integer");
}
else if (double.TryParse(input, out double doubleResult))
{
Console.WriteLine("Double");
}
else
{
Console.WriteLine("String");
}
*Okay, so technically double (and every floating point number type) can't represent every integer perfectly, because of how they're implemented in binary, but that's a whole other topic and too advanced for now, if you ever want to know more, check out Is floating point math broken?
Well, you can try else if instead of just if. Please, note, that every int can be parsed as double and every char can be treated as string:
if (int.TryParse(input, out int result1))
Console.WriteLine("type int");
else if (double.TryParse(input, out double result2))
Console.WriteLine("type double");
else if (input.Length == 1) // char is a string of Length == 1
Console.WriteLine("type char");
else
Console.WriteLine("type String");
In your statements, there are two different condition blocks. Therefore, you will get two outputs. If you only want to get one output. You should use one condition block: If, Else If, Else.
string input = Console.ReadLine();
if (int.TryParse(input, out int result1))
{
Console.WriteLine("type int");
}
else if (double.TryParse(input, out double result2))
{
Console.WriteLine("type double");
}
else
{
Console.WriteLine("type String");
}
Console.ReadLine();
You can use Convert class to Convert int to double
int n1 = 289;
double n2;
n2 = Convert.ToDouble(n1);

Argument 2 may not be passed with the 'out' keyword

I am new at programming, I am trying to insert values inside four arrays using one for loop. However I only get the error: (Argument 2 may not be passed with the 'out' keyword. I know that's something wrong around the console readline but I don't what I can do to turn around this situation. That's my code so far:
int size;
do
{
Console.Clear();
Console.Write("What is the size of the array: ");
} while (!int.TryParse(Console.ReadLine(), out size));
string[] name = new string [size];
double[] grade1 = new double [size];
double[] grade2 = new double[size];
double[] avarage = new double [size];
for (int i = 0; i < size; i++)
{
do
{
Console.Write($"Insert the name of student number: {i + 1}: ");
} while (!Convert.ToString(Console.ReadLine(), out name[i]));
do
{
Console.Write($"Insert {i + 1}ยบ grade: ");
} while (!Convert.ToDouble(Console.ReadLine(), out grade1[i]));
}
While int.TryParse returns a bool, Convert.ToString and Convert.ToDouble do not, and unlike other languages, C# won't let you treat other types as bool to shorthand null comparisons. Thus, you generally can't use !value when value is not a bool.
Note that in the case of the second conversion, you're converting a string (console input) to a string, so it's not necessary - just take the string and check for IsNullOrWhitespace (although you'll need multiple line). Thus
do
{
Console.Write($"Insert the name of student number: {i + 1}: ");
name[i] = Console.ReadLine();
} while (string.IsNullOrWhitespace(name[i]));
For the third conversion, you could use double.TryParse instead,
} while(!double.TryParse(Console.ReadLine(), out grade1[i]));
Notably, most of the numerical types in .NET support TryParse methods, and converting a string to a string just to make code look the same is a good example of the YAGNI principle.

Converting Celcius to Fahrenheit - Double.TryParse

I have a successful clean code that does a conversion of Celcius to Fahrenheit using Double.Parse. However, I was curious on how it would look if I did a Double.TryParse but I can't seem to figure out how to complete the code. Once executed, I am able to present "Invalid Code", in my "if, else" but I still get this after my Invaild Output...
Please enter a value for conversion:
30x
Invalid code
The conversion from Celcius to Fahrenheit is: 32
using System;
using System.Text;
namespace CSharpBasics
{
class Program
{
public static double CelciusToFarenheit(string celciusTemperature)
{
//Converting string to a double for conversion
double celcius;
if (Double.TryParse(celciusTemperature, out celcius))
{
}
else
{
Console.WriteLine("Invalid code");
}
double fahrenheit = (celcius * 9 / 5) + 32;
return fahrenheit;
}
public static void Main(string[] args)
{
Console.WriteLine("Please enter a value for conversion:");
var input = CelciusToFarenheit(Console.ReadLine());
Console.WriteLine("The conversion from Celcius to Fahrenheit is: " + input);
}
}
}
You should verify your input before the conversion to make sure you never display invalid result for an invalid input but return a message notifying the wrong input first. Something like this:
public static double CelciusToFarenheit(double celcius)
{
double fahrenheit = (celcius * 9 / 5) + 32;
return fahrenheit;
}
public static void Main(string[] args)
{
Console.WriteLine("Please enter a value for conversion:");
var input = Console.ReadLine();
double celcius;
if (Double.TryParse(input, out celcius))
{
var result = CelciusToFarenheit(celcius);
Console.WriteLine("The conversion from Celcius to Fahrenheit is: " + result);
}
else
{
Console.WriteLine("Invalid code");
}
}
The method signature public static double CelciusToFarenheit(...) says that this method returns a value - and currently it does.
However, your program flow has to consider invalid input - and thus you need 2 information:
was the entered value a valid value
what's is the value
There are different methods to solve this issue, at least the following:
return a struct or object that holds both information
use the return value and indicate invalid results with exceptions
split the single method into 2 methods, one for checking validity and one for delivering the value.
Let's discuss the 3 options:
3) This might be looking nice, but when you look at Double.TryParse(), you'll likely introduce duplicate code. And when you look at the Main method, the abstraction level will not be the same.
2) Exceptions shall be used for exceptional cases. Wrong user input seems to be a rather usual thing. Not ideal for this case.
1) Sounds quite ok, except that the method might be responsible for 2 things: checking validity and calculating.
To implement that, you don't even need to write a new struct or class. You can simply use Nullable<double> or double?.
Since you're talking about clean code (potentially referring to R.C. Martin), I would start by looking at the main method. Basically I would say the code follows the IPO principle (input, processing, output). However, one line does 2 things:
var input = CelciusToFarenheit(Console.ReadLine());
Also, the variable name input is not so useful here, because it's not the input of the user, but the output after processing.
Proposal for that part:
public static void Main(string[] args)
{
var userInput = GetCelsiusInputFromUser();
var output = CelciusToFarenheit(userInput);
PrintOutput(output);
}
Also, the conversion method does not only convert, but print partial results as well:
Console.WriteLine("Invalid code");
I'd remove that piece and leave it to the output method to handle that case.
Full code:
using System;
namespace CSharpBasics
{
class Program
{
public static double? CelciusToFarenheit(string celciusTemperature)
{
//Converting string to a double for conversion
double celcius;
if (Double.TryParse(celciusTemperature, out celcius))
{
double fahrenheit = (celcius * 9 / 5) + 32;
return fahrenheit;
}
else
{
return null;
}
}
public static void Main(string[] args)
{
var userInput = GetCelsiusInputFromUser();
var output = CelciusToFarenheit(userInput);
PrintOutput(output);
}
private static void PrintOutput(double? output)
{
if (output == null)
{
Console.WriteLine("Invalid code");
}
else
{
Console.WriteLine("The conversion from Celcius to Fahrenheit is: " + output);
}
}
private static string GetCelsiusInputFromUser()
{
Console.WriteLine("Please enter a celsius value for conversion:");
var userInput = Console.ReadLine();
return userInput;
}
}
}
BTW: if you don't have a technical issue, https://codereview.stackexchange.com/ might be better suited for questions regarding clean code.

working with console writeline c#

I need to output the value of d using the same Console.WriteLine. But i am only getting Result not the value of d in output. In what way i can achieve this?
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
int a;
int b;
Console.WriteLine("Please Enter the first Digit");
a = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Please Enter the Second Digit");
b = Convert.ToInt32(Console.ReadLine());
int d = a + b;
Console.WriteLine("Result",(d));
}
}
}
Use:
Console.WriteLine("Result {0}", d);
You are using this overload.
UPDATE
If you look at the link above, you can read how it works. In short, first you specify the formatting, where {0} references the first value of the param object-array, {1} references the second value of the param object-array, etc. After the format, you give the objects to use.
So in your case, you need a single value, which means two arguments, a format, and a value. Hence "Result {0}" with d, which will become (when for example d=10) "Result 10".
Note: also removed the unnecessary parenthesis.
Use
Console.WriteLine("Result {0}", d);

Categories

Resources