I'm trying to make a program that takes a number and print it on screen but if the user press enter the code ask the user to enter the number again but instead it shows me a exception
Enter_No:
Console.WriteLine("enter number");
int? n = Convert.ToInt32(Console.ReadLine());
if (n == (int?)null)
{
goto Enter_No;
}
else
{
Console.WriteLine(n);
}
Use int.TryParse:
int? num = null;
while(!num.HasValue)
{
Console.WriteLine("Please enter an integer:");
num = int.TryParse(Console.ReadLine(), out int i) ? i : new int?();
}
Console.WriteLine("Entered integer: " + num.Value);
Tim's solution is wonderfully compact. Here's why your attempt failed.
From MSDN, Convert.ToInt32() throws a FormatException if:
value does not consist of an optional sign followed by a sequence of digits (0 through 9).
The preferred approach is int.TryParse(), as it returns false if it's unable to parse the integer rather than throwing an exception.
While the goto keyword is supported in C#, there are few or no situations (depending on who you ask) where it's the best option for flow control. Tim's while loop is an excellent approach.
First, don't use Go To:
Second: Inspect your data and use tryparse:
bool success = false;
do
{
Console.WriteLine("enter number");
var n = Console.ReadLine();
if (n == null)
{
// goto Enter_No;
}
else
{
int typedNum;
success = int.TryParse(n, out typedNum);
Console.WriteLine(typedNum);
}
} while (!success);
Related
I am trying to create a check answer button. I have not learned how to use methods yet so i cannot use them in this. I first need to check if the math operation is subtraction or addition and then go from there. Visual studio does not detect any errors but when i run the program and try to check the answer ive inputted i get an error telling me unhandled exception has occured and that input string was not in correct format. I have a feeling the proble is with my int lblMath but im not sure how else to check what the value is inside of that lbl.
{
int First = int.Parse(lblFirst.Text);//The first number in the math equation
int Second = int.Parse(lblSecond.Text);//The second number in the math equation
int UserAnswer = Convert.ToInt32(txtAnswer.Text);//The users answer to math question
int lblMath = int.Parse(lblMathType.Text);//Whether the symbol is + or -
if(lblMath == '+')
{
int AnswerAdd = First + Second;
//Answer is addition
if(UserAnswer == AnswerAdd)
{
MessageBox.Show("Correct");
}
else if(UserAnswer != AnswerAdd)
{
MessageBox.Show("Wrong Answer");
}
}
else if (lblMath == '-')
{
int AnswerSub = First - Second;
//Answer is subtraction
if(UserAnswer == AnswerSub)
{
MessageBox.Show("Correct");
}
else if (UserAnswer != AnswerSub)
{
MessageBox.Show("Wrong Answer");
}
}
You're expecting this to be an integer:
int lblMath = int.Parse(lblMathType.Text);
But then you're immediately expecting it to be a string:
if(lblMath == '+')
(I'm honestly surprised this even compiles.)
What integer value to you expect the string "+" to be and why? The exception is telling you that the string "+" is not an integer. Because it isn't.
It's a string. Use it as a string:
string lblMath = lblMathType.Text;
I want to ask the user to input a number including an if statement option were if he puts letters the last question will be asked again
I've tried this but seemingly it work only for strings
Console.Write("Write a number:");
int num = Convert.ToInt32(Console.ReadLine());
if (!int.TryParse(age, out num))
while(!int.TryParse(age, out num))
{
Console.WriteLine(...);
// ....
}
Let's extract method for this: we are going to ask user to input valid value until he or she provides it. So we have a loop:
private static int ReadInteger(string question) {
// Keep asking...
while (true) {
if (!string.IsNullOrWhiteSpace(question))
Console.WriteLine(question);
// ... until valid value provided
if (int.TryParse(Console.ReadLine(), out int result))
return result;
Console.WriteLine($"Sorry, not a valid integer value; please, try again.");
}
}
Then you can use it as
int age = ReadInteger("Please, input age");
I have a function that I'm using in my current project that might help you out, it just checks if the input string only contains numbers:
bool isDigitsOnly(string inputString)
{
foreach (char c in inputString)
{
if (c < '0' || c > '9')
return false;
}
return true;
}
You might have to modify it a little bit to fit your needs, but it should work well enough
I can't figure out how to check whether the input is a specific letter. I know how to check if it's a specific int/double but when it's a string I don't know what to do.
Any help would be greatly appreciated. I'm just trying to make a basic 3 question quiz that checks whether the user answers with the correct letter (a, b or c) and then adds that to the current score.
class Program
{
static void Main()
{
var a1 = "a";
var a2 = "b";
var a3 = "c";
var qa = 0;
while (qa != 3)
{
if (qa == 0)
{
Console.Write("What is the answer to question 1? ");
var entry1 = Console.Read();
if()
{
}
}
else if (qa == 1)
{
Console.Write("What is the answer to question 2? ");
Console.ReadLine();
}
else if (qa == 2)
{
Console.Write("What is the answer to question 3? ");
Console.ReadLine();
}
}
}
}
For example operator == can't be applied to strings
this is not true. It can be applied:
if(entry.ToString() == a1)
The documentation for the == operator tells us:
For the string type, == compares the values of the strings
another possibility would be to use the String.Equals method
if(entry.ToString().Equals(a1))
EDIT:
Looking closer at your code I realized that you are using Console.Read
which
Reads the next character from the standard input stream.
That means that it returns a char (and only 1).
I guess you want the entire line that the user types in. So you should use ReadLine instead. It returns a string and allows you for a direct comparison
string entry1 = Console.ReadLine();
if(entry == a1)
when you use var for the declaration of types the compiler infers the type and the error becomes obvious at a later stage. you cannot use the == operator on string and char . Read() returns a char so that's why you were not able to compare it in the first place
Note that in "Question 1" you wrote Console.Read(), (not Console.ReadLine()) which returns a char, not a string. So "==" cannot be applied to entry1 and a1 since entry1 will be a char while a1 is a string.
If you compare compatible variables, everything should be fine
string input1;
var input2 = "";
var input3 = 0;
// assign some input values, then compare
// strings
if (input1 == "a") // ok
{ }
if (input2 == "a") // ok
{ }
if (input3 == "a") // not ok, comparing int to string
{ }
// numbers
if (input1 == 1) // not ok, comparing string to int
{ }
if (input3 == 1) // ok
{ }
If you want to, you could try matching the ASCII value of the character by using Console.Read();. This would eliminate the need to press enter. If you were trying to match to uppercase A:
int input = Console.Read();
if (input == (int)char.GetNumericValue(A))
{
Console.WriteLine("True");
Console.Read();
}
else
{
Console.WriteLine("False");
Console.Read();
}
static void Main(string[] args)
{
int output = 0;
int number = 0;
Console.WriteLine("Please input a number for it to be counted!");
bool conversion = int.TryParse(Console.ReadLine(), out output);
if( number >= 1000)
{
while (number <= output)
{
switch (conversion)
{
case true:
Console.Write(number + " ");
number += 2;
break;
case false:
Console.WriteLine("ERROR INVALID INPUT!");
break;
}
}
}
else
{
Console.WriteLine("APPLICATION ERROR: NUMBER MUST BE BELOW OR AT 1000 TO PREVENT OVERFLOW!");
}
string choice = Console.ReadLine();
do // Here is the beginning of the do code
{
Console.WriteLine("Do you want to continue - Yes or No");
if(choice.ToUpper() != "NO" && choice.ToUpper() != "NO");
{
Console.WriteLine("ERROR INVALID INPUT: Only input Yes or No!");
}
}while(choice.ToUpper() != "YES" && choice.ToUpper() != "NO");
}
}
}
This is a very simple application and is unfinished but what it does is you put in a number below or equal to 1000 and it counts up to it evenly. My only problem is with the do statement at the end of the code. Its unfinished but from what I've researched that do statement is completed what happens is if the user does not input yes or no it will show them that error and then ask again "do you want to go again" However because of this do statement I put in any number like 10 and it gives me the error saying its over 1000 and then goes on an infinite loop of saying "ERROR INVALID INPUT: ONLY INPUT YES OR NO!" How can I fix this?
Your if statement tests for NOT EQUAL to "no" twice, I assume you mean to check for not equal to "YES" and not equal to "NO"
Your infinite loop is because the condition checks the content of choice, but you never change the value of the variable within the do loop - only in the Console.ReadLine() immediately before the loop starts.
You should start the do loop before the code you want to be repeated. For instance, if your intent is that if the user types yes that the entire process repeats, you may be best served by creating a void function, say static void CountNumbers() { ... } that has all the code doing your input on how high to count, error handling, etc. Then you can use your do loop to easily repeat as much as the user wants, like this:
string choice = null;
do
{
CountNumbers();
// Your code here to ask if user wants to continue and readline to get the new choice
} while ( /* Existing condition */);
You have several issues in the code:
First, your condition checks that number is GREATER than or equal to 1000. Since you're entering 10, which is not >= 1000, then you get to the else statement. So you need to change your condition to:
if(number <= 1000)
Next, your condition in the do loop checks the same condition twice... you don't allow the user to enter "yes". You should modifiy the condition to include a check for "yes". Also, you need to remove the semi-colon from the end of that same if statement:
do
{
Console.WriteLine("Do you want to continue - Yes or No");
choice = Console.ReadLine();
if(choice.ToUpper() != "NO" && choice.ToUpper() != "NO");
{
Console.WriteLine("ERROR INVALID INPUT: Only input Yes or No!");
}
} while(choice.ToUpper() != "YES" && choice.ToUpper() != "NO");
One thing you also might consider is adding a method to get an integer from the user, since it is handy to wrap it in some validation:
public static int GetIntFromUser(string prompt,
string errorMessage = "Invalid entry. Please try again.")
{
int value;
while (true)
{
if (prompt != null) Console.Write(prompt);
if (int.TryParse(Console.ReadLine(), out value)) break;
if (errorMessage != null) Console.WriteLine(errorMessage);
}
return value;
}
Then, you can call this method when you need to get an int from the user. Here's a sample of how it could be used:
private static void GenericTester()
{
// This will flag that the user wants to quit
bool quit = false;
while(!quit)
{
// Get input from user
int userInput = GetIntFromUser("Please input a number to be counted: ");
int number = 0;
// Write out the numbers
if (userInput <= 1000)
{
while (number <= userInput)
{
Console.Write(number + " ");
number += 2;
}
}
else
{
Console.WriteLine("APPLICATION ERROR: NUMBER MUST BE BELOW " +
"OR AT 1000 TO PREVENT OVERFLOW!");
}
// See if they want to continue
while (true)
{
// Get user input
Console.Write("Do you want to continue - Yes or No: ");
string choice = Console.ReadLine();
// If they said 'No', set flag to quit and break out of this loop
if (choice.Equals("No", StringComparison.OrdinalIgnoreCase))
{
quit = true;
break;
}
// If they said 'Yes', just break out of this loop
if (choice.Equals("Yes", StringComparison.OrdinalIgnoreCase)) break;
// Otherwise, display an error message and let the loop continue
Console.WriteLine("ERROR INVALID INPUT: Only input Yes or No!");
}
}
}
I am trying to write a simple program that asks the user to enter a number and then I will use that number to decide what the cost of the ticket will be for their given age. I am having trouble when trying to convert the string to int. Otherwise the program layout is fine. Any suggestions?
thanks
using System;
class ticketPrice
{
public static void Main(String[] args)
{
Console.WriteLine("Please Enter Your Age");
int input = Console.ReadLine();
if (input < 5)
{
Console.WriteLine("You are "+input+" and the admisson is FREE!");
}
else if (input > 4 & input < 18)
{
Console.WriteLine("You are "+input+" and the admission is $5");
}
else if (input > 17 & input < 56)
{
Console.WriteLine("You are "+input+" and the admission is $10");
}
else if (input > 55)
{
Console.WriteLine("You are "+input+" and the admission is $8");
}
}
}
Try the int.TryParse(...) method. It doesn't throw an exception.
http://msdn.microsoft.com/en-us/library/f02979c7.aspx
Also, you should use && not & in your conditions. && is logical AND and & is bitwise AND.
For easy parsing of strings to integers (and other number types), use that number type's .TryParse(inputstring, yourintegervariable) method. This method will output a Boolean (True/False), letting you know whether the operation passed or failed. If the result is false, you can give an error message before going any further (don't have to worry about crashing your program).
Previous text concerning switch statements has been removed
In C#, you need to use the && operator for logical AND. & is not the same and may not work the way you believe it will.
I suggest to use the Int32.TryParse() method. Further I suggest to refactor your code - you can make it much cleaner (assuming this is not just example code). One solution is to use a key value pair list to map from age to admission.
using System;
using System.Collections.Generic;
using System.Linq;
static class TicketPrice
{
private static readonly IList<KeyValuePair<Int32, String>> AgeAdmissionMap =
new List<KeyValuePair<Int32, String>>
{
new KeyValuePair<Int32, String>(0, "FREE!"),
new KeyValuePair<Int32, String>(5, "$5."),
new KeyValuePair<Int32, String>(18, "$10."),
new KeyValuePair<Int32, String>(56, "$8.")
};
public static void Main(String[] args)
{
Console.WriteLine("Please Enter Your Age!");
UInt32 age;
while (!UInt32.TryParse(Console.ReadLine(), out age)) { }
String admission = TicketPrice.AgeAdmissionMap
.OrderByDescending(pair => pair.Key)
.First(pair => pair.Key <= age)
.Value;
Console.WriteLine(String.Format(
"You are {0} and the admission is {1}",
age,
admission));
}
}
I used an unsigned integer to prevent entering negative ages and put the input into a loop. This way the user can correct an invalid input.
int number = int.Parse(Console.ReadLine());
Be aware that this will throw an exception if they enter an invalid number.
The first thing you need to do is change your input variable to a string:
string input = Console.ReadLine();
Once you have that, there are several ways to convert it to an integer. See this answer for more info:
Better way to cast object to int