If else Statment not working - c#

Hi my If statement wont work for some reason I want it to say invalid if user goes below 0 or over 100 but every number i put in goes directly to my else statement doesn't even notice my if statement.
What am I doing wrong?
g:
Console.WriteLine("Enter Grade: ");
int grade = Convert.ToInt32(Console.Read());
if (grade < 0 || grade > 100)
{
Console.WriteLine("Input Valid");
Console.ReadLine();
}
else
{
Console.WriteLine("Input invalid");
Console.ReadLine();
}
goto g;

if/else is not a problem here. The way you're getting input from user is.
Use Console.ReadLine() instead of Console.Read():
int grade = Convert.ToInt32(Console.ReadLine());
Console.Read returns numeric representation (ACII code) of the first character from console, not the number you've typed itself.

Some changes you might need to do:
int grade = Convert.ToInt32(Console.ReadLine());
and change your condition to &&:
if (grade >= 0 && grade <= 100)

Change your read statement as follows:
int grade = Convert.ToInt32(Console.ReadLine());
Console.Read() returns the ASCII code that you typed, while Console.ReadLine() returns a string.

Related

Switch jumping to default case [duplicate]

This question already has answers here:
Difference between Console.Read() and Console.ReadLine()?
(12 answers)
Closed 1 year ago.
I don't get why my integer isn't coming out correctly, Console.Read() method says it's returning an integer, why isn't WriteLine displaying it correctly?
int dimension;
dimension = Console.Read();
Console.WriteLine(""+ dimension);
Console.Read() only returns the first character of what was typed. You should be using Console.ReadLine():
Example:
int suppliedInt;
Console.WriteLine("Please enter a number greater than zero");
Int32.TryParse(Console.ReadLine(), out suppliedInt);
if (suppliedInt > 0) {
Console.WriteLine("You entered: " + suppliedInt);
}
else {
Console.WriteLine("You entered an invalid number. Press any key to exit");
}
Console.ReadLine();
Additional Resources:
MSDN - Console.Read()
MSDN - Console.ReadLine()
From the MSDN:
Return Value
Type: System.Int32 The next character from the input stream, or
negative one (-1) if there are currently no more characters to be
read.
Your program is returning but you're not seeing, would you please see below code block:
You are not be able to see the output if the output window doesn't stay.
int dimension;
dimension = Console.Read();
Console.WriteLine("" + dimension);
Console.ReadLine();
Console.Read() returns ASCII code of first symbol in input. You can do
int dimension;
dimension = Console.Read();
Console.WriteLine(""+ (char)dimension);
and you'll see right first symbol in input, as
(char)dimension
will give you symbol by it's ASCII code.
int a = 0;
if(Int32.TryParse(Console.ReadLine(), out a))
{
// Do your calculations with 'a'
}
else
{
// Some warnings
}
The Console.Read method returns only a single character wrapped in an int, so that is only applicable if you are reading a number that is only one digit long, otherwise you'll always get only the first digit.
Since the return value of Read is actually a character, you cannot use it directly as an integer, you would need to parse it from character to integer.
But assuming that you want a number that is longer than one digit, then you really need to use Console.ReadLine instead and convert the input to an integer using int.TryParse. If int.TryParse returns false you can warn the user that he provided an invalid input and ask for the dimension again.
Sample code:
int dimension;
bool isValidDimension;
do
{
Console.Write("Dimension: ");
string input = Console.ReadLine();
isValidDimension = int.TryParse(input, out dimension);
if (!isValidDimension)
{
Console.WriteLine("Invalid dimension... please try again.");
Console.WriteLine();
}
} while (!isValidDimension);
you should it as follow
static void Main()
{
int Number;
string strNumber;
strNumber = Console.ReadLine();
Number = int.Parse(strNumber);
Console.WriteLine("" + dimension);
}

How to build a loop that allows a user to input positive and whole numbers and ends when 0 or negative numbers are input

Hello good people.
So I am struggling a little with the while/for/do while loops as I am having trouble understanding their structure.
And that causes me to have some issues with my homework assignment , what I need to do is a write a code for the following:
I need a program that allows a user to input only positive and whole numbers , the program also calculates their sum and shows the result for each input in the console ( for example the user inputs 1 and than 2 and than 3 and than 4 the program will show the result as 10).
The program will end if the user has input 0 or a negative number.
I can only use for / while / do while.
My experience is really with only the basic stuff like int , double , loop , string , etc'
I can't really wrap my head around it very much and I would love to get some ideas and assistance.
I've tried but got stuck at the beginning has I have no idea how to start with it
edit:
I've really just dabbled with the idea because I have no idea how to start , I've made this, it was no good
int number, i=1 , min;
Console.WriteLine("Please enter only positive WHOLE numbers to calculate");
number = int.Parse(Console.ReadLine());
while (i <= number)
{
Console.WriteLine("This is the smallest number: " + number);
i++;
}
edit: I did this, but I wonder if there's a better way
int number, sum = 0;
Console.WriteLine("Please enter only positive WHOLE numbers to calculate");
start:
number = int.Parse(Console.ReadLine());
while (number > 0)
{
Console.WriteLine("This is your number : " + number);
sum += number;
Console.WriteLine("The sum is: " + sum);
goto start;
}
while (number <= 0)
{
Console.WriteLine("Please enter a number bigger than 0");
break;
}
Loops are for code that repeats. In your task, input and addition repeat, so put them in loop. while and for loops check the condition before executing loop body, and do checks after.
Your algorithm is like that:
Read input.
Check if it's positive, if it's not, exit.
Add it to sum.
Repeat.
So you should check the condition in the midst of loop. You can use break to exit loop early. Since you neither check condition in beginning nor end, just write an infinite loop.
int n, sum = 0;
while (true) {
n = int.Parse (Console.ReadLine ());
if (n <= 0) break;
sum += n;
}
Updated. Yes you can shorten your code.
int number, sum = 0;
Console.WriteLine("Please enter only positive WHOLE numbers to calculate");
start:
number = int.Parse(Console.ReadLine());
You put a repeating statement outside of loop. It forced you to use a label. Labels can easily make your logic very difficult to read.
while (number > 0)
{
Console.WriteLine("This is your number : " + number);
sum += number;
Console.WriteLine("The sum is: " + sum);
goto start;
You exit the loop indefitinely, so that's no difference between while and if here.
}
while (number <= 0)
{
Console.WriteLine("Please enter a number bigger than 0");
break;
And the same again.
}
Remember to use loop when something repeats and don't use when nothing does.
Console.WriteLine ("Please enter only positive WHOLE numbers to calculate");
int n, sum = 0;
while (true) {
n = int.Parse (Console.ReadLine ());
Console.WriteLine ("This is your number : " + number);
if (n <= 0) {
Console.WriteLine("Please enter a number bigger than 0");
// actually he won't get a chance to enter it. Why to ask him then?
break;
}
sum += n;
Console.WriteLine("The sum is: " + sum);
}
1 way of doing it:
int number, i=0 , min=1; // min is the minimum value, i is the sum, number is the input you give
while (i <= min)// checks if its lesser than zero
{
Console.WriteLine("Please enter only positive WHOLE numbers to calculate");
number = int.Parse(Console.ReadLine());
i += number;
Console.WriteLine("This is the sum: " + i);
}
Other way of doing it:
int number, i=0 , min=1; // min is the minimum value, i is the sum, number is the input you give
while (true)
{
Console.WriteLine("Please enter only positive WHOLE numbers to calculate");
number = int.Parse(Console.ReadLine());
if(i<=min)
break;
i += number;
Console.WriteLine("This is the sum: " + i);
}
I think the best thing to do is read the documentation:
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/while
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/do

c# cant run two functions in a loop?

What i want to do is to make it that inside a loop, the computer checks whether the number entered is firstly not a decimal, and at the same time i want to make sure that the number is within the range 1 - 100. My code now works in regards to having the first function about the number not being a decimal, so when i enter a decimal, an error message is displayed that tells the user to keep adding another number until an integer is added, and it then runs to the next part. However it doesn't seem to work when i put in a number outside of the range, the error message doesn't pop up and the conditions just don't seem to work. What i want to know is how do i get these two parts, the decimal and the range checking to work simultaneously. I'm really new to coding so could any explanations be simple so that i could understand. Thank you in advance!
string inputcost;
string inputmoney;
int validcost;
int validmoney;
int changereq;
Console.Write("Please Enter The Cost, In Pennies, Of The Item You Have Purchased: ");
inputcost = Console.ReadLine();
bool result = int.TryParse(inputcost, out validcost);
while (!int.TryParse(inputcost, out validcost))
{
if (result == true )
{
Console.Write("Valid Value");
}
if (result == false)
{
Console.Write("You Cannot Enter Decimals. Please Enter A Valid Integer Value.");
Console.WriteLine();
inputcost = Console.ReadLine();
}
if (validcost < 100 && validcost > 1)
{
Console.Write("valid value");
}
else
{
Console.Write("invalid value.please enter a number between 1 and 100 ");
Console.ReadLine();
}
}
The line
while (!int.TryParse(inputcost, out validcost))
means that you enter the while loop only when the user types something that cannot be converted to an integer. If it is a valid integer the code inside the while loop is never reached and thus, your test on the valid range is never executed
Instead put everything inside the an infinite loop and provide a way to break the program (type x to quit)
while (true)
{
Console.Write("Please Enter The Cost, In Pennies, Of The Item You Have Purchased: (type x to quit)");
inputcost = Console.ReadLine();
// Check if the user wants to stop executing the program
if(inputcost == "x")
break;
// Check if it is a valid integer
bool result = int.TryParse(inputcost, out validcost);
if (!result)
{
Console.WriteLine("You Cannot Enter Decimals (or strings). Please Enter A Valid Integer Value.");
}
else if (validcost > 100 || validcost < 1)
{
Console.WriteLine("invalid value.please enter a number between 1 and 100 ");
}
else
{
Console.WriteLine("Valid value");
// other code block that works with the input number....
}
}
Alternativly use another condition for your loop, something that first checks for an integer and afterwards if it is in range:
while (!int.TryParse(inputcost, out validcost)) || validCost < 1 || validCost > 100)
{
Console.WriteLine("Please enter an integer between 1 and 100");
inputCost = Console.ReadLine();
}
All the code that should be executed when your inout is valid should now gow beyond the loop, not inside it.

Operator '>' and '<' cannot be applied to operands of type 'string' and 'string' C#

C# program made in Visual Studio 2015 that asks the user to guess a number from 1-10 that will tell the user if the guess was right, greater than or lesser than the value that must be guessed.
static void Main(string[] args)
{
string rightGuess = "7";
Console.WriteLine("Guess the right number from 1-10: ");
string userGuess;
userGuess = Console.ReadLine();
{
if (userGuess == rightGuess)
Console.WriteLine("You guessed right!");
else if (userGuess > rightGuess)
Console.WriteLine("Wrong guess. Your guess was greater than the right guess.");
else (userGuess < rightGuess)
Console.WriteLine("Wrong guess. Your guess was lesser than the right guess.");
}
}
The program returns following errors in Visual Studio 2015:
Have researched about an hour on Google how to solve the errors but none of the solutions fixed the errors.
You need to compare integers rather than strings (to achieve that kind of compare), change this lines to:
int rightGuess = 7;
int userGuess = int.Parse(Console.ReadLine());
and it will work. Of course you can add int.TryParse and check if input was actually an int
int userGuess;
if(int.TryParse(Console.ReadLine(), out userGuess))
{
... do your logic
}
else
{
Console.WriteLine("Not a number");
}
You should be using the right data type to compare
int rightGuess = 7;
Console.WriteLine("Guess the right number from 1-10: ");
int userGuess;
userGuess = int.Parse(Console.ReadLine());
{
if (userGuess == rightGuess)
Console.WriteLine("You guessed right!");
else if (userGuess > rightGuess)
Console.WriteLine("Wrong guess. Your guess was greater than the right guess.");
else (userGuess < rightGuess)
Console.WriteLine("Wrong guess. Your guess was lesser than the right guess.");
}
Think like this when you say "Mohit" is greater than "Mikex64" does it make any sense. No
But 2 is greater than 1 make sense. thus we can write it like 2 > 1 but cannot write "Mohit" > "Mikex64" thus you are getting this error message.
Edit: edited the "greater than" and "lesser than" operands from code to be accurate as I first wrote them wrong way.
either convert the string to numeric values using int.Parse/TryParse or use String.CompareTo().

C#.NET While loop not exiting

This is a short function to check and make user write uppercase Y or N .I dont know why but even if the user enter upper case Y or N , still then the loop does not exit. Any help please?
static char GetUpperCaseYN()
{
char choice='y';
Console.WriteLine("Calculate Another? Y/N ");
choice = char.Parse(Console.ReadLine());
while (choice != 'Y' || choice != 'N')
{
Console.WriteLine("Invalid Response.Please enter Y or N");
choice = char.Parse(Console.ReadLine());
}
return choice;
}
Use && not ||; they can't both be false with one character :)

Categories