Argument 2 may not be passed with the 'out' keyword - c#

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.

Related

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

Cannot implicitly convert string to int

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)

Why am I printing out 'System.Int32[]' instead of my array of numbers? [duplicate]

This question already has answers here:
C# multidimensional arrays iteration
(5 answers)
Closed 2 years ago.
I am trying to print out my array of numbers that I have assigned to a particular array. My algorithm for choosing numbers consists of choosing a random number that is not a duplicate and storing it inside the array.
Pretty simple really, but I have no idea as to why it is printing out this error.
int[] ticket1 = new int[4];
for (int i = 0; i < 4; i++)
{
int temp = rand.Next(43);
while (ticket1.Contains(temp))
{
temp = rand.Next(43);
}
ticket1[i] = temp;
}
Console.WriteLine("{0}{1}", item.PadRight(20), ticket1.ToString());//ticket1 produces System.Int32[] instead of 4 numbers.
//I have changed this line to:
//Console.WriteLine("{0}{1}", item.PadRight(20), string.Join(",", ticket1));
//And it still doesn't work. the error remains. (System.Int32[])
My question is, how can I print out my 4 numbers (beside each other) in string format.
//EDIT: I've found my problem. I am putting my ticket1 inside a foreach loop, it's somehow not reaching out to the array values and it therefore prints out System.Int32[] instead.
All fixed.
If you call ToString() on an array like that, you simply get the full name of the type of class.
You could fix it a few ways. Print only the current item inside the loop, or print each item one at a time outside of the loop:
Console.WriteLine("{0}{1}", item.PadRight(20), ticket1[0]);
Console.WriteLine("{0}{1}", item.PadRight(20), ticket1[1]);
// etc...
Or "flatten" the collection before printing:
Console.WriteLine("My numbers: ", String.Join(", ", ticket1));
ticket1.ToString() does not print the content of the array, only its type, because this is the way the ToString() method is implemented on arrays.
You can fix this in several ways - for example, by using string.Join method:
Console.WriteLine("{0}{1}", item.PadRight(20), string.Join(",", ticket1));
Because you are not writing your array elements, you are writing your array itself, that's why ToString() generates it's full type name.
Change your ticket1.ToString() to ticket1[i] in your for loop.
for (int i = 0; i < 4; i++)
{
int temp = rand.Next(43);
while (ticket1.Contains(temp))
{
temp = rand.Next(43);
}
ticket1[i] = temp;
Console.WriteLine("{0} {1}", item.PadRight(20), ticket1[i]);
}
If you don't want to print it inside your for loop, then you can use String.Join to concatenate all your elements in your array in a simple string like;
for (int i = 0; i < 4; i++)
{
int temp = rand.Next(43);
while (ticket1.Contains(temp))
{
temp = rand.Next(43);
}
ticket1[i] = temp;
}
Console.WriteLine("{0} {1}", item.PadRight(20), string.Join(",", ticket1));
Because when you call .ToString() on an object you get the type of that object. For basic primitive (value) types this behavior is overridden to output the value. But for something like an array there's no "default" string representation, so the behavior you're seeing is the default.
You could wrap your data in an object and override .ToString() on that object. If you have to output the values in many places in the code that would be the way to go so you only have to write the logic once. ("Smart data structures and dumb code works a lot better than the other way around." - Eric Raymond)
But if you only need to do it here then you can just output the values directly. Basically join the values as a string in whatever representation you want. For example, if they should be comma-separated:
Console.WriteLine(
"{0}{1}",
item.PadRight(20),
string.Join(",", ticket1));

C# using dynamic for both decimal and double

I have an assignment where the I gotta figure out a way to make the input read both double and decimal and perform a few operations as new method.
char[] charSeparators = new char[] { ' ' };
Console.Write("Please type few numbers: ");
dynamic[] test = Console.ReadLine().Split(charSeparators, StringSplitOptions.RemoveEmptyEntries).ToArray();
dynamic value = test[0];
for (int i = 1; i < test.Length; i++)
{
if (test[i] < value)
{
value = test[i];
}
}
I figured out to use dynamic as data type, but this throws an exception:
Operator '<' cannot be applied to operands of type 'string' and 'string'
I already made a fallback using a switch where the user selects if it's double or decimal but I thought this was way more simple.
How to stop that dynamic from being read as string ?
Note that the split method always returns an array of strings, so you have to convert it results. The problem isn't the Dynamic.
Example:
char[] charSeparators = new char[] { ' ' };
Console.Write("Please type few numbers: ");
dynamic[] test = Console.ReadLine().Split(charSeparators, StringSplitOptions.RemoveEmptyEntries).ToArray();
double value = double.Parse(test[0]);
for (int i = 1; i < test.Length; i++)
{
if (double.Parse(test[i]) < value)
{
value = double.Parse(test[i]);
}
}
try this:
var value= Convert.ToDecimal( test[0])
or
var value= Convert.ToDouble( test[0])
because test[0] is a string, so when you define it as dynamic, its type binds in run time but makes no difference because its type is clear in compile-time and no need to define it as dynamic.
You are taking the console input which will be a string. In order to turn in into any sort of numeric value you need to parse it.
dynamic[] test = Console.ReadLine().Split(charSeparators, StringSplitOptions.RemoveEmptyEntries).ToArray(); will be a string array, so you'll need to cast it to a decimal or a double.
I'm not sure how you're going to figure out whether it's double of decimal, so why not cast them all to decimal, since that type keeps its precision.
Your current array contains strings. You need to convert them to decimals or doubles
dynamic[] test = Console.ReadLine().Split(charSeparators, StringSplitOptions.RemoveEmptyEntries).ToArray().Select(double.Parse).ToArray();

C#- Getting user input for Age.. but receiving error?

I am trying to make improve my programming and getting things drilled into my head so I'm just quickly developing an application that gets user's input and prints their name. But also gets their input for "Age verification".
I'm practicing IF & ELSE statements as well as nesting classes.
However my compiler is shooting me an error and I just cannot seem to figure it out. I'm trying to get the user to input his age, and then proceed with the IF & ELSE statement.
Compiler is shooting error that . ""Cannot implicitly convert type
string to int"
The only error in the program right now is the
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;
}
}
As the error says you can't implicitly type a string to an int. You need to parse it into an 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
}
You are trying to assign a string value to an int with this line:
myCharacter.age = Console.ReadLine();
Try:
myCharacter.age = Int32.Parse(Console.ReadLine());
character.age expects an Int but ReadLine() returns a string, you need to look at using int.Parse or int.TryParse to avoid exceptions
e.g.
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!");
}
This looks like a student project.
The input coming from the ReadLine() is always of type string. You're then comparing a string to 17 which isn't valid, as 17 is an int. Use TryParse versus parse to avoid throwing an exception at runtime.
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. The problem here is that the age is defined as an int and Console.ReadLine() always returns a string so thus you have to convert the user input from string to integer in order to correctly store the age.
Something like this:
myCharacter.age = Int32.Parse(Console.ReadLine());
When you read input from the console, it returns it to you in the form of a string. In C#, which is a statically typed language, you cannot simply take one type and apply it to another type. You need to convert it somehow, there are several ways to do this.
The first way would be casting:
myCharacter.age = (int)Console.ReadLine();
This won't work because a string and an integer are two completely different types and you can't simply cast one to the other. Do some reading on casting types for more information.
The second way would be to convert it, again there are a couple of ways to do this:
myCharacter.age = Int32.Parse(Console.ReadLine());
This will work as long as you type in an actual number, in this case the Parse method reads the string and figures out what the appropriate integer is for you. However, if you type in "ABC" instead, you will get an exception because the Parse method doesn't recognize that as an integer. So the better way would be to:
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;
In this case the TryParse method tries to parse it, and instead of throwing an exception it tells you it can't parse it (via the return value) and allows you to handle that directly (rather than thru try/catch).
That's a little verbose, but you said you're learning so I thought I'd give you some stuff to consider and read up on.

Categories

Resources