Characters not returning - c#

How to fix the errors with characters in C# Employee class I am making. I know how to handle string, int, and double. The char.Parse doesn't cooperate.
public static string AskForLastName()
{
string inValue;
Console.Write("Enter last name: ");
inValue = Console.ReadLine();
return inValue; //works fine
}
public static char AskForGender()
{
char inValue;
Console.Write("Enter gender: ");
inValue = Console.ReadLine();//error here for some reason
return (char.Parse(inValue));//error here for some reason
}
public static int AskForNoDependendents()
{
string inValue;
Console.Write("Enter the dependents: ");
inValue = Console.ReadLine();
return (int.Parse(inValue));//works fine
}
public static double AskForAnnualSalary()
{
string inValue;
Console.Write("Enter annual salary: ");
inValue = Console.ReadLine();
return (double.Parse(inValue));//works fine
}

Console.ReadLine() returns a string. You can't implicitly convert that to a character- what if someone enters "Male" or " M" (preceded by one or more spaces).
Your AskForGender method is going to need to be smarter about what input it accepts, and how it parses that input.
If you really need a character out of this (to satisfy the assignment, or whatever), then you need to figure out a way to get from all of the possible String inputs ("Male", "MALE", "Female", "Horse", "Dog", "4", etc.) to either:
An acceptable Character (presumably 'M' or 'F', but maybe others?)
or
An error condition, whereupon maybe you print a nice error message and ask them to re-enter?

Description
Console.ReadLine returns a string. You can use string[] to get the first character of your string. But you have to make sure that the user inserts at least one character.
Sample
public static char AskForGender()
{
while (true)
{
Console.Write("Enter gender (m/w): ");
string inValue = Console.ReadLine();
// check that the user inputs a character
if (!string.IsNullOrEmpty(inValue) && (inValue[0] == 'm' || inValue[0] == 'w'))
return inValue[0];
}
}
Update
My sample covers now that the user inputs m or w.
Update
It is homework so...
If your Teacher ask "But what happens if the user inputs a M instead of m? You should say "It asks the user again".
If your Teacher asks then "How to make it possible to accept M and m? You should say i can make it case insensitive.
Sample
You should use i can use .NET's .ToUpper() method.
.ToUpper() - Returns a copy of this string converted to uppercase.
public static char AskForGender()
{
while (true)
{
Console.Write("Enter gender (m/w): ");
string inValue = Console.ReadLine();
// check that the user inputs a character
if (!string.IsNullOrEmpty(inValue) && (inValue.ToUpper()[0] == 'M' || inValue.ToUpper()[0] == 'W'))
return inValue.ToUpper()[0]; // returns M or W
}
}

You're trying to pull a string into a char. Console.ReadLine() returns a string.
If you need specifically one character (Presumably M or F) consider making your inValue a string, trimming it (to ensure there are no leading spaces), and then returning inValue[0] (which should be a char)
Something like:
string inValue = Console.ReadLine();
inValue = inValue.Trim();
return inValue[0];
**Note- that's not the best way to do it, but it should make the idea fairly clear.

According to MSDN ReadLine returns a string - you can't assign a string to a char!

Related

Ternary operator in a while loop in C#

I'm very new to programming and I was wondering how could I break out the loop if the number is valid with a ternary operator? I'm used to do it with if-else but in this case I don't know the proper syntax to do it or if it is possible.
Thanks!
while (!valid)
{
.....
Console.Write("Enter your phone number : ");
string noTelephone = Console.ReadLine();
string message = ValiderTelephone(noTelephone) ? "Numéro valide" : "Numéro invalide";
}
I'd go the way that Magnetron indicated in the comments if you're desperate for something that uses a ternary, but realistically there isn't any point in arranging the code lol you have/setting the message if you're going to loop until it's valid, because you don't use the message you set! This means that by the time the code reaches a point where message could be used for something, it must surely be "Number valid"
How about:
Console.WriteLine("Enter number:");
string num = Console.ReadLine();
while(!ValidNumber(num)){
Console.WriteLine("Invalid number, try again:");
num = Console.ReadLine();
}
string message = "Number valid";
Or better:
private string Ask(string question){
Console.WriteLine(question);
return Console.ReadLine();
}
...
string num = Ask("Enter number:");
while(!ValidNumber(num))
num = Ask("Invalid number, try again:");

How to remove a series of individual letters from a string?

Messing around with C# logic, trying to build a program where the user inputs a string, and then has the option to decide which letter is removed from said string.
Console.WriteLine("Please enter a string of letters");
string input = Console.ReadLine();
Console.WriteLine("please enter letters you would like removed");
char removedLetters = Convert.ToChar(Console.ReadLine());
foreach (char letter in input)
{
Console.WriteLine(input.Replace(removedLetters,' ').ToLower());
}
This works, but not entirely. I will get rid of characters, but only when written in a specific way that corresponds with the original input.
e.g helloworld -> remove l = he owor d
but helloworld -> remove elo = failure.
Can someone share some knowledge? Really trying to get better at logic, happy i got this far just need bit of guidance.
Cheers,
Andy
Expanding on Jasen's comment from earlier something like this ...
Console.WriteLine("Please enter a string of letters");
string input = Console.ReadLine();
List<char> input_array = input.ToList();
Console.WriteLine("please enter letters you would like removed");
string removedLetters = Console.ReadLine();
char[] remove_array = removedLetters.ToArray();
for (int k = 0; k < remove_array.Count(); k++)
{ input_array.RemoveAll(r=>r== remove_array[k]); }
Console.WriteLine(new string(input_array.ToArray()));
Again, using Linq, in this case RemoveAll, to automate the heavy lifting. I have not tested how efficient these are, they are quick and simple solutions not necessarily the most efficient.
Not sure how you want to handle duplicates but C# has an Except operator that works on Arrays. So convert both strings to an array and something like this should work...
Console.WriteLine("Please enter a string of letters");
string input = Console.ReadLine();
char[] input_array = input.ToArray();
Console.WriteLine("please enter letters you would like removed");
string removedLetters =Console.ReadLine();
char[] remove_array = removedLetters.ToArray();
char[] leftover_array = input_array.Except(remove_array).ToArray();
Console.WriteLine(new string(leftover_array));

What do I use to convert string into unicode

I am having an issue with this block of code.
Console.WriteLine("What is your name?");
string PlayerName = Convert.ToInt32(Console.ReadLine());
Console.WriteLine(PlayerName);
What I'm trying to do is get the computer to read the name you input, and ask you if that is your name. Directly after I type my name though there is an exception. Convert.ToInt32 isn't what I'm supposed to use, and I guess my question is what do I put there instead.
I am new to programming and I'm not even sure if it's called unicode. Sorry.
Console.ReadLine() will return a string, no need to do any conversions:
Console.WriteLine("What is your name?");
string PlayerName = Console.ReadLine();
Console.WriteLine(PlayerName);
Convert.ToInt32() throw casting error if you do not pass valid integer value inside it. So, you need to check it gracefully and get interger value. For that, you can Int32.TryParse(input, out val) and get integer value.
Ex :
int value;
if(Int32.TryParse(your_input, out value))
{
// if pass condition, then your input is integer and can use accordingly
}
So, your program will be like this if you want to print integer value only :
Console.WriteLine("What is your name?");
var value = Console.ReadLine();
int intVal;
if(Int32.TryParse(value, out intVal))
{
Console.WriteLine(intVal);
}
If you want only to print what you've got from ReadLine method, you can just have :
Console.WriteLine("What is your name?");
Console.WriteLine(Console.ReadLine());
Convert.ToInt32(String) "Converts the specified string representation of a number to an equivalent 32-bit signed integer". You are getting an error because you are not typing in an integer value in your console.
Your PlayerName variable is of type string, and the return value of Console.ReadLine() is already a string, so you don't need any conversion.
If you’re dealing with Unicode characters, you might have to set proper encoding like so
Console.InputEncoding = Encoding.Unicode;
Console.OutputEncoding = Encoding.Unicode;
Console.WriteLine("What is your name?");
string PlayerName = Console.ReadLine();
Console.WriteLine(PlayerName);

C#. Input string was not in a correct format

I'm new in the community and I'm learning C#. I try to write a program and faced with the problem below. I tried to find the answer in Google and here but no luck yet. When I choice "Y" I'm getting the error.
I attached the code and screenshot, please help if you can, thank you!
using System;
namespace YourAge
{
internal class Age
{
public static void Main()
{
DateTime newDataTime = DateTime.Now;
Console.WriteLine("So, today is " + "{0}", newDataTime);
Console.Write("Do you smoke a cigarettes? Y/N: ");
char Y = (char)Console.Read();
if (Char.IsUpper(Y))
{
Console.Write("How many cigarettes do you smoke in the day?: ");
int cigTotal = Convert.ToInt16(Console.ReadLine());
//cost of one cigarettes
float costOneCig = 0.3F;
float sumTotal = cigTotal * costOneCig;
Console.WriteLine("You are losing every day:{0:C2}", sumTotal);
}
else
//coming soon
Console.ReadKey();
}
}
}
This is the exception thrown:
The problem is that you are using Console.Read() instead of Console.ReadLine().
Console.Read() only reads the next character from standard input. Console.ReadLine(), on the other hand, reads the entire line of characters from the standard input stream and then moves to the next newline.
When you press 'Y' and then enter, when you get up to the next Console input, Convert.ToInt16(Console.ReadLine(), the Console is still up to the previous input line.
Possible solutions:
Change (char)Console.Read() to Covert.ToChar(Console.ReadLine()). ReadLine takes in an entire string, not a char, so you need to use Convert.ToChar instead of the simple (char) cast to convert the first character of the string into a char.
Add a blank Console.ReadLine() after (char)Console.Read() to tell the Console to flush to the next line.
Input your character together with the next number like "Y2" (although I highly doubt this is what you want to do).
string userInput = Console.ReadLine();
int numberOfCigarettes = Convert.ToInt16(userInput);
This might make it more visible for you what is the problem.
Console.ReadLine() returns a string which you later need to convert into an integer. If your userInput string is not a number, then conversion is impossible and an exception is thrown.
On the other hand your if statement is incorrect as well. Right now you are only checking the variable Y whether it is uppercase not whether it holds a literal character 'y'.
You could for example make sure that the variable Y is always uppercase like this:
if(Y.ToUpper().Equals('Y'))
You may want to try something like this so you can diagnose the problem. Please make sure to mark an answer if it is correct.
Console.Write("Do you smoke a cigarettes? Y/N: ");
string answer = Console.ReadLine();
while (answer.Length != 1) {
Console.WriteLine("Character is one letter silly.");
Console.Write("Do you smoke a cigarettes? Y/N: ");
answer = Console.ReadLine(); }
char response = answer[0];
if (response == 'Y' || response == 'y')
{
//YES RESPONSE
}
else
{
//NO RESPONSE
}
Console.ReadLine();
This code will let you know if you input anything else other than one character. Good luck with C#!

Writing an executable function in C#

I'm really new to all of this. I need to write an exe application in C#. What i need to do is to be able to pass values through the console into a function. But I'm unsure as to how I can store the values that are entered through the console...
I know we can use Read() to read what has been entered but, when I'm dealing with multiple values how do i do this?
Any help will be greatly appreciated!! Thanks in advance
You start with choosing the Console Application template (in New Project)
And then, in the Main function, you can read a line at a time with
string line = Console.ReadLine();
This probably shifts your question to : How do I get values from a string?
If you have a single int at a time, it is
int x = int.Parse(line);
Are you referring to passing command line parameters to a console application? If so, there is a string array parameter (e.g. args) that holds them. See this code.
static void Main(string[] args)
{
}
You can also use Environment.GetCommandLineArgs.
Hmm I think he is wondering how to repeatitly read some value and pass it to a function.
For that you can use a simple while loop.
string data = Console.ReadLine();
do {
dummyFunction(data);
data = Console.ReadLine();
} while (data != "");
You want to programmatically compile text into code? If so you should read this KB entry from Microsoft. How to programmatically compile code using C# compiler
Or if you want to get input from the user in the console, you should use Console.ReadLine().
Console.Write("Enter your name: ");
string name = Console.ReadLine();
Console.Write("Enter your age: ");
int age = int.Parse(Console.ReadLine());
Console.Write("Hello {0}, you are {1} years old.", name, age);
You can basically do a parsing work manually. For example, if the input is a name follows by age.
Natthawut 22
You can use Console.ReadLine() to get the string "Nattawut 22". And then use String.Split(' '); to get an array of {"Natthawut","22"}. Then convert the second element to integer using Convert.ToInt32(val);
I believe there must be a better way to do this but this is how I usually do it :)
int year, month, day;
Console.WriteLine("Please enter your birth year : ");
year = int.Parse(Console.ReadLine());
Console.WriteLine("Please enter your birth month : ");
month = int.Parse(Console.ReadLine());
Console.WriteLine("Please enter your birth day : ");
day = int.Parse(Console.ReadLine());
Console.Write("You are ");
Console.Write(CalculateAge(year, month, day));
Console.Write(" years old.");
An alternative way is this:
Console.WriteLine("Please enter your birthday in the format YY-MM-DD : ");
string line = Console.ReadLine();
string[] parts = line.Split(new char[] { '-' });
int age = CalculateAge(parts[0],parts[1],parts[2]);
Console.WriteLine("You are {0} years old.", age);
And -PLEASE- do some input checking.

Categories

Resources