I have a fairly specific question on this otherwise functional piece of code. The problem is that whenever I run it, there is always a blank spot after the value, so the user has to enter their input twice. So the output would say...
pic related
public string GetPayType()
{
Console.WriteLine("Please enter 1 if your pay type is a weekly hourly wage and 2 if your pay type is a monthly salary:");
if (Console.ReadLine() == "1")
{
payType = Convert.ToString(Console.ReadLine());
return payType;
}
else if (Console.ReadLine() == "2")
{
payType = Convert.ToString(Console.ReadLine());
return payType;
}
else
{
Console.WriteLine("Error! You may only enter a 1 or a 2!");
}
return payType;
}
By doing the line below again after comparing the first input, you are basically prompting for another input to return.
payType = Convert.ToString(Console.ReadLine());
return payType;
Try:
public string GetPayType()
{
Console.WriteLine("Please enter 1 if your pay type is a weekly hourly wage and 2 if your pay type is a monthly salary:");
payType = Console.Readline();
if (payType == "1" || payType == "2")
{
return payType;
}
else
{
Console.WriteLine("Error! You may only enter a 1 or a 2!");
}
return null;
}
You might as well want to add a loop for the user if they entered an invalid input, I'll leave that to you for your own research.
Related
So I wanted to make a sort of “name checker” that’s always had the first letter be capital and the rest lowercase. I got that to work but whenever I got past the name checker and wanted to use the name in future code, it would always say “string may be null here.” I have tried many things like adding a ? But nothing works. I don’t think it can be null but maybe I’m wrong. Here is my code here:
class Program
{
static void Main()
{
string? name, choice;
bool finishnameingcharacter;
finishnamingcharacter = true;
while(finishingnamingcharacter == false)
{
Console.WriteLine("Enter your name");
name = Console.ReadLine();
name = name?.ToLower();
if(name != null)
{
name = char.ToUpper(name[0]) + name.Substring(1);
}
Console.WriteLine("");
Console.WriteLine("Your name is " +name+ ", is that correct?");
Console.WriteLine("");
Console.WriteLine("1: Yes");
Console.WriteLine("2: No");
choice = Console.ReadLine();
if(choice == "1")
{
finishnamingcharacter = 1;
}
if(choice == "2")
{
Console.WriteLine("");
}
else
{
Console.WriteLine("Invalid Claim")
}
}
Console.WriteLine(name);
}
}
The "name" at the bottom is where the error is. If there's any confusion about my question ask me. I tried my best to explain it.
I could not compile your code, so I made some changes
static void Main()
{
var name = string.Empty;
var choice = string.Empty;
do
{
Console.WriteLine("Enter your name");
name = Console.ReadLine();
name = name?.ToLower();
if (name != null && name.Length>1)
name = char.ToUpper(name[0]) + name.Substring(1);
Console.WriteLine("");
Console.WriteLine("Your name is " + name + ", is that correct?");
Console.WriteLine("");
Console.WriteLine("1: Yes");
Console.WriteLine("2: No");
choice = Console.ReadLine();
if (choice == "1") break;
if (choice == "2")Console.WriteLine("");
else Console.WriteLine("Invalid Claim");
} while (true);
Console.WriteLine(name);
}
Why use a nullable string in this software?
You didn't initialize the name at the beginning, if your loop will never run, then the name output line will be NULL. This is what your error points to.
It is better to initialize variables before their first use, as they can be NULL by default (valid for reference types such as classes). For a string, one option would be String.Empty
string name = String.Empty, choice = String.Empty;
These two lines can be combined:
bool finishnameingcharacter;
finishnamingcharacter = true;
// Replaced by
bool finishnameingcharacter = true;
On the next line in the while loop, you check the condition: finishingnamingcharacter == false. The loop checks the condition and only then executes. To execute the loop, you need the condition to be TRUE, but it will not take this value, because earlier you defined the variable finishnamingcharacter = true. true != false. By default you need to define this variable as false
bool finishnameingcharacter = false;
The user can enter an empty string value, so converting it to lowercase immediately doesn't matter, as long as it checks for an empty string. There is a special method for checking if a string is empty: string.IsNullOrEmpty() - it returns true if the string is empty or null.
If the user entered the wrong name, then we need to ask him to enter again, for this, the continue operator is used.
name = Console.ReadLine();
if(string.IsNullOrEmpty(name) || string.IsNullOrWhiteSpace(name))
{
Console.WriteLine("Sorry, your name is empty. Please enter again.")
continue;
}
//So if name is not empty: jOhN
name = name.ToLower(); //john
name = char.ToUpper(name[0]) + name.Substring(1); //John
For boolean values it is better to use reserved words, i.e. instead of finishnamingcharacter = 1 it is better to write finishnamingcharacter = true
Rest of the code looks good. We all took the first steps :)
Full modified code here:
class Program
{
static void Main()
{
string name = String.Empty choice = String.Empty;
bool finishnameingcharacter = false;
while(finishingnamingcharacter == false)
{
Console.WriteLine("Enter your name");
name = Console.ReadLine();
if(string.IsNullOrEmpty(name) || string.IsNullOrWhiteSpace(name))
{
Console.WriteLine("Sorry, your name is empty. Please enter again.")
continue;
}
//So if name is not empty: jOhN
name = name.ToLower(); //john
name = char.ToUpper(name[0]) + name.Substring(1); //John
Console.WriteLine("");
Console.WriteLine("Your name is " +name+ ", is that correct?");
Console.WriteLine("");
Console.WriteLine("1: Yes");
Console.WriteLine("2: No");
choice = Console.ReadLine();
if(choice == "1")
{
finishnamingcharacter = true;
}
else if(choice == "2")
{
Console.WriteLine("");
}
else
{
Console.WriteLine("Invalid Claim")
}
}
Console.WriteLine(name);
}
}
PS There is a special method TextInfo.ToTitleCase() "wAr aNd pEaCe to titlecase: War And Peace" - I advise you to read
I am very new to C# and I have just created my first program, which is your classic "number guesser".
In my program, after the user has guessed the correct number, I want to give them an option where they can either type "Y" or "N" to continue or end the game.
Where my issue lies is, if the user were to type in the letter "G" at this stage, the program would continue and ask the user to input another number.
How do I enable my code to keep looping at this stage until either Y is pressed to continue the game or N is pressed to end the program?
using System;
// Namespace
namespace NumberGuesser
{
// Main Class
class Program
{
// Entry Point Method
static void Main(string[] args)
{
GetAppInfo(); // Run GetAppInfo function to get info
GreetUser(); // Ask for user's name and greet
while (true)
{
// Create a new Random object
Random random = new Random();
// Initial correct number
int correctNumber = random.Next(1, 11);
// Initial guess var
int guess = 0;
// Ask user for number
Console.WriteLine("Guess a number between 1 and 10:");
// While guess is not correct
while (guess != correctNumber)
{
// Get users input
string input = Console.ReadLine();
// Make sure it's a number
if (!int.TryParse(input, out guess))
{
// Print error message
PrintColourMessage(ConsoleColor.Red, "Please user an actual number.");
// Keep going
continue;
}
// Make sure the number guessed is between 1 - 10
if (guess > 10)
{
// Print error message
PrintColourMessage(ConsoleColor.Red, "Please enter a number from 1 to 10.");
// Keep going
continue;
}
// Cast to int and put in guess
guess = Int32.Parse(input);
// Match guess to correct number
if (guess != correctNumber)
{
// Print error message
PrintColourMessage(ConsoleColor.Red, "Wrong number, please try again.");
}
}
// Print success message
PrintColourMessage(ConsoleColor.Yellow, "You are CORRECT!!!");
// Ask to play again
Console.WriteLine("Play again? [Y or N]");
// Get answer
string answer = Console.ReadLine().ToUpper();
if (answer == "Y")
{
continue;
}
else if (answer == "N")
{
return;
}
else
{
return;
}
}
}
// Get and display app info
static void GetAppInfo()
{
// Set app vars
string appName = "Number Guesser";
string appVersion = "1.0.0";
string appAuthor = "Jack Thomas";
// Change text colour
Console.ForegroundColor = ConsoleColor.Green;
// Write out app info
Console.WriteLine("{0}: Version {1} by {2}", appName, appVersion, appAuthor);
// Reset text colour
Console.ResetColor();
}
// Ask user's name and greet
static void GreetUser()
{
// Ask users name
Console.WriteLine("What is your name?");
// Get user input
string inputName = Console.ReadLine();
Console.WriteLine("Hello {0}, let's play a game...", inputName);
}
// Print colour message
static void PrintColourMessage(ConsoleColor color, string message)
{
// Change text colour
Console.ForegroundColor = color;
// Prints message
Console.WriteLine(message);
// Reset text colour
Console.ResetColor();
}
}
}
Just instead of doing this:
// Ask to play again
Console.WriteLine("Play again? [Y or N]");
// Get answer
string answer = Console.ReadLine().ToUpper();
if (answer == "Y")
{
continue;
}
else if (answer == "N")
{
return;
}
do that:
// Ask to play again
Console.WriteLine("Play again? [Y or N]");
bool toContinue = false;
bool invalidResponse = true;
while(invalidResponse) {
// Get answer
string answer = Console.ReadLine().ToUpper();
if (answer == "Y")
{
toContinue = true;
invalidResponse = false;
}
else if (answer == "N")
{
invalidResponse = false;
}
}
if(toContinue != true) return;
I've created while loop wich loops while invalidResponse variable is true, invalidResponse is true when we not entered any of these characters "Y" or "N".
You can also make Console.WriteLine when user enters invalid response.
If user does not entered "Y" it sets toContinue to false and it ends program.
I apologize if this has already been answered else where, I've looked but couldn't find anything. Also this is my first time ever asking a programming related question, I'm really bad with articulating. I'm working on it. Thank you in advanced!
Is it possible to skip the next lines asking for input, to the if statement if input is exit?
while (isAdding == true)
{
Console.Write("First Name: ");
input = Console.ReadLine();
Console.Write("Last Name: ");
input2 = Console.ReadLine();
Console.Write("Address: ");
input3 = Console.ReadLine();
Console.Write("Phone Number: ");
input4 = Console.ReadLine();
Console.Write("Email Address: ");
input5 = Console.ReadLine();
if (input == "exit" || input2 == "exit" || input3 == "exit" || input4 == "exit" || input5 == "exit")
{
isAdding = false;
//break;
}
With your current syntax, you need to check for the input values on every step.
Console.Write("First Name: ");
input = Console.ReadLine();
if(input == "exit"){
break;
}
Console.Write("Last Name: ");
input2 = Console.ReadLine();
if(input2 == "exit"){
break;
}
If you're purpose is to stop the iteration after all the inputs are saved, then your code is sufficient.
A cleaner way is putting the evaluation inside a function.
public bool ShouldExit(string firstName, string lastName){
if(firstName == "exit" || lastName == "exit"){
return true
}
}
Then call that function instead.
if (ShouldExit(input,input2))
{
isAdding = false;
//break;
}
I'm trying to make a simple odd/even number program, but I want to compare did user entered number. When I enter any symbol which is not a number I get second exception, but when I just press enter ie. not giving any value, I still get a second except except the first one, which I'm trying to get when I don't give any value. My question is how to get a first exception text when I just press enter, since right now I only get second one, whatever I enter.
Console.WriteLine("Enter a number: ");
try
{
var number = int.Parse(Console.ReadLine());
if (number % 2 == 0)
Console.WriteLine($"Entered number {number} is even.");
else
Console.WriteLine($"Entered number {number} is odd.");
}
catch (ArgumentNullException)
{
Console.WriteLine("You need to enter some value.");
}
catch (Exception)
{
Console.WriteLine("You need to enter a number.");
}
You should catch FormatException in case you just press enter as string.Empty is being passed to int.Parse. ArgumentNullException is being thrown only if the input value which was passed to int.Parse is null. Here is example how you can do this and write different messages depending on the inputed value:
Console.WriteLine("Enter a number: ");
string input = Console.ReadLine();
try
{
var number = int.Parse(input);
if (number % 2 == 0)
Console.WriteLine($"Entered number {number} is even.");
else
Console.WriteLine($"Entered number {number} is odd.");
}
catch (FormatException exc)
{
if(string.IsNullOrEmpty(input))
{
Console.WriteLine("You need to enter some value.");
}
else
{
Console.WriteLine("You need to enter a number.");
}
}
catch (Exception exc)
{
Console.WriteLine("You need to enter a number.");
}
Try this:
var str = Console.ReadLine();
if (string.IsNullOrEmpty(str))
{
Console.WriteLine("You need to enter some value.");
}
else
{
int number;
if (!int.TryParse(str, out number))
{
Console.WriteLine("You need to enter a number.");
}
else
{
if (number % 2 == 0)
Console.WriteLine($"Entered number {number} is even.");
else
Console.WriteLine($"Entered number {number} is odd.");
}
}
If you don't enter any value, the value is not null but ""(empty string), that's why it's not an ArgumentNullException
Do how George Alexandria suggested
string s = Console.ReadLine();
if(s == "")
{ Console.WriteLine("You need
to enter some value."); }
Not sure if I'm overlooking something really simple but I'm trying to make a program that allows a user to enter 1 of 2 letters and then run code based on the input. Seems simple enough but I've run into several errors with all the ways I thought this could work. Here is the code:
string name = (Console.ReadLine());
Console.WriteLine("Is " + name + " ok?");
Console.WriteLine("\n(Y)es\n(N)o");
char ansys = Console.ReadKey();
if (ansys = ConsoleKey.Y)
Console.Clear();
else
{
Console.WriteLine();
Console.WriteLine("Enter letters only");
}
I added in the else portion (unfinished)just to get an idea if If i'm going the right direction with the intended goal as well. Would I be able to make an else statement that triggers if neither Y or N is pressed this way?
Well, first of all, you are making an assignment, not comparing:
if (ansys.Key = ConsoleKey.Y)
is wrong, use:
if (ansys.Key == ConsoleKey.X)
== is comparison, = is assignment. Don't confuse them, it may cause serious problems.
For you question, if you simply add an else if statement checking for "No" answer, then else statement won't be triggered if Y or N is pressed. If at least if statement is executed, else statement won't be executed.
Your code should look like:
if (ansys == ConsoleKey.Y) {
// code if yes
}
else if (ansys == ConsoleKey.N) {
// code if no
}
else {
// code if neither
}
Edit:
Since my primary language is not C#, I looked at documentation to check my answer. I figured out that if you use ReadKey() it does not return a ConsoleKey, it returns struct ConsoleKeyInfo. You need to use Key member of the ConsoleKeyInfo to access the pressed key. Please re-check the code.
Try this approach:
ConsoleKeyInfo cki;
cki = Console.ReadKey();
if (cki.Key == ConsoleKey.Y)
{
Console.Clear();
}
else if (cki.Key == Console.N)
{
Console.Clear();
}
else
{
Console.WriteLine();
Console.WriteLine("Enter letters only");
}
You can find th examples here: ReadKey - examples
Try this:
string name = (Console.ReadLine());
Console.WriteLine("Is " + name + " ok?");
Console.WriteLine("\n(Y)es\n(N)o");
var ansys = Console.ReadKey();
if (ansys.KeyChar == 'y' || ansys.KeyChar == 'Y')
{
//Handle yes case
}
if (ansys.KeyChar == 'n' || ansys.KeyChar == 'N')
{
//Handle no case
}
else
{
Console.WriteLine();
Console.WriteLine("Enter letters only");
}
Try this (couldnt test it)
This will ask for the name until the confirmation answer is Y
If the input when asked Y or N is another thing, it will ask again for the name confirmation.
string name = "";
while (name.equals(""))
{
name = (Console.ReadLine());
Console.WriteLine("Is " + name + " ok?");
String answer = "";
while(answer.equals(""))
{
Console.WriteLine("\n(Y)es\n(N)o");
char ansys = Console.ReadKey();
if (ansys == ConsoleKey.Y || ansys == ConsoleKey.N)
{
answer = ansys.ToString();
Console.Clear();
}
else
{
Console.WriteLine();
Console.WriteLine("Enter letters only!!");
}
}
if(!answer.equals("Y"))
name = "";
}
Im not sure if ansys.ToString() is a valid method, and if that returns the "Y" string in case the key pressed was Y