Please help i have got very confused with the if statement below - c#

I want the user to input a number, but if it is below zero I would like to show an error message and then loop round and ask the user for another number. Here is the code I have at the moment.
// this determines what the loop does.
for (int CustPos = 0; CustPos < LineNum; CustPos = CustPos + 1)
{
// this asks the user to enter the sales figures
Console.Write("enter sales figures for" + customer[CustPos] + " ");
// this is user's input is read in and stored.
sales_figures[CustPos] = Double.Parse(Console.ReadLine());
if (sales_figures[CustPos] < MIN_SALES_FIGURE) //True - continue
{
Console.WriteLine("");
Console.WriteLine("entry invalid");
Console.WriteLine("enter another value");
}
else//FALSE -> Go back to start of loop
{
Console.WriteLine("");
}
//this section displays the cust name, sales figure 70/30.
Console.WriteLine(" ");
fee_payable[CustPos] = (sales_figures[CustPos] / 100.0)
* licence_fee_in_percent[CustPos];
Console.WriteLine(customer[CustPos] +
" ----------- " + fee_payable[CustPos]);
Console.WriteLine("Licence fee to be paid in GBP is :" +
fee_payable[CustPos]);
seventy_percent_value = ((fee_payable[CustPos] / 10.0) * 7);
Console.WriteLine("70 percent of this fee is" +
seventy_percent_value);
thirty_percent_value = ((fee_payable[CustPos] / 10.0) * 3);
Console.WriteLine("30 percent of this fee is" +
thirty_percent_value);
Console.WriteLine(" ");
}
. Please help all advice will be greatly appreciated!
Thanks

I think a do-while loop would be better here, pseudocode:
userInput = -1
do
{
userInput = Console.ReadLine
}
while (userInput <0)
Colin E.

Youre on the right track, just look at the keyword Continue
This is the example in the link:
using System;
class ContinueTest
{
static void Main()
{
for (int i = 1; i <= 10; i++)
{
if (i < 9)
{
continue;
}
Console.WriteLine(i);
}
}
}
Note: The continue statement passes control to the next iteration of the enclosing iteration statement in which it appears.

if (sales_figures[CustPos] < MIN_SALES_FIGURE) //True - Continue //FALSE -> Go back to start of loop
You don't actually have any code here to make it go back to the start of the loop.
I recommend that you write it all out as pseudocode first, then turn it into code:
if (number entered is too low)
then restart loop
otherwise carry on

Instead of an if, you'll want a while:
while( sales_figure[CustPos] < 0 )
{
Console.Write("enter sales figures for" + customer[CustPos] + " ");
sales_figures[CustPos] = Double.Parse(Console.ReadLine());
}
Which guarantees that it will keep prompting until they enter something greater than zero.
Continue, does NOT do what you want it to. Continue means, "move on and ignore this iteration" which means you'd have an incorrect value for that customer.

Use a WHILE loop in combination with your IF:
continueflag = 0;
while (continueflag == 0)
{
sales_figures[CustPos] = Double.Parse(Console.ReadLine());
Console.WriteLine("");
if (sales_figures[CustPos] >= MIN_SALES_FIGURE) {
Console.WriteLine("entry invalid");
Console.WriteLine("enter another value");
} else continueflag = 1;
}

Related

How to prevent input of null enter in C# [duplicate]

This question already has answers here:
check for valid number input - console application
(5 answers)
Allow To Only Input A Number - C#
(1 answer)
Closed 2 years ago.
I have just started a table programme. I am just a trainee learning C# from internet, so I am not so good in this.
I just wanted the programme to run according to the user. I want that if the user hits enter simply, the programme should not crash. That is I just wanted to know how to prevent null enter. This is the code is used:
The "______" which used if for writing a line
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace tables
{
class Program
{
static void Main(string[] args)
{
goto found;
found:
Console.WriteLine("");
string textToEnter = "MULTIPLATION TABLES";
Console.WriteLine(String.Format("{0," + ((Console.WindowWidth / 2) + (textToEnter.Length / 2)) + "}", textToEnter));
Console.WriteLine("");
Console.WriteLine("________________________________________________________________________________");
Console.WriteLine("");
int num, j, i;
Console.Write("enter the number of which table u need ? :- ");
num = Convert.ToInt32( Console.ReadLine());
while (num == 0)
{
Console.WriteLine("please enter a valid input");
Console.Write("enter the number of which table u need ? :- ");
num = Convert.ToInt32(Console.ReadLine());
}
Console.Write("enter the number till which the table need to be ? :- ");
j = Convert.ToInt32(Console.ReadLine());
while (j == 0)
{
Console.WriteLine("please enter a valid input");
Console.Write("enter the number till which the table need to be ? :- ");
j = Convert.ToInt32(Console.ReadLine());
}
i = Convert.ToInt32(j);
for (j=1; ; j++)
{
if (j > i)
{
break;
}
Console.WriteLine(num + " * " + j + " = " + num * j);
}
string str;
Console.Write("do you want to continue? (y/n) :- " );
str= Console.ReadLine();
foreach (char ch in str)
{
if (ch == 'y')
{
goto found;
}
else if (ch=='n' )
{
Console.WriteLine("");
Console.WriteLine("THANK YOU FOR USING MY PRODUCT");
}
else
{
Console.WriteLine("please enter a valid input");
}
}
Console.ReadKey();
}
}
}
As suggested in the comments, I'd use int.TryParse(), but inside a do...while() loop. Use a separate flag (boolean) to track whether the user should keep trying again:
bool invalid;
int num, j, i;
do
{
invalid = true;
Console.Write("enter the number of which table u need ? :- ");
String response = Console.ReadLine();
if (int.TryParse(response, out num))
{
invalid = false;
}
else
{
Console.WriteLine("Invalid input. Please try again.");
}
} while (invalid);
// ...repeat the above do...while() block for "j" and "i"...
When you're accepting user input, it's important to perform validation on it. You can't assume that the user will always enter correctly formatted data that your program will be able to work with. As you discovered, a user who hits enter will give you an empty string (""), which can't be parsed to anything.
C# has several ways of attempting parsing. The first, which you're using, is Convert.ToInt32(), which throws an exception if the input it receives is not, in fact, a number. You have to catch the exception with a try/catch block, like so:
try
{
num = Convert.ToInt32(Console.ReadLine());
}
catch(FormatException ex)
{
Console.WriteLine("You didn't enter a proper number!");
}
However, in general, exceptions should be, well, exceptional. They should only be relied upon when rare failures occur, because unwinding the call stack can be expensive.
I would argue that C# has a better method for you to use in this instance: Int32.TryParse()
You can see the documentation here.
TryParse takes two parameters, the thing you're trying to parse (convert), and then a number to store the value in. It returns true or false, indicating if it succeeded or failed in converting the number.
You might use it like this:
var success = Int32.TryParse(Console.ReadLine(), num);
if (success)
{
// do something with 'num' -- it has a valid value now.
}
else
{
// Warn the user, perhaps prompt them to try again
Console.WriteLine("That wasn't a valid number!");
}
You can use a methode to get a safe int value:
private static int ReadIntValue(string psMessage)
{
int lnInt;
string lsValue = string.Empty;
do
{
Console.Write(psMessage);
lsValue = Console.ReadLine();
} while (!int.TryParse(lsValue, out lnInt));
return lnInt;
}
And then use this:
num = ReadIntValue("enter the number of which table u need ? :- ");

C# while loop not functioning [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I am trying to build a stimulate income tax calculator. The progress I am wanting to make is :
print out a message of "What is your total income :" to ask user to input their income in positive numeric number.
to read their inputs
make a loop: if the user put in strings, print "Enter your income as a whole-dollar numeric number",and go back to step 1. If the user put in negative number, print "Your income cannot be negative",and go back to step 1.
4.if the user has successfully enter the positve numeric number, process to step 5.
print out a message "How many children do you have?"
read the user's input.
make a loop: if the user types in strings, print "You must enter a valid number", and go back to step 5. If the user types in negative number, print "You must enter a positive number", and go back to step 5.
if the user successfully enter the postive numeric number, process to step 9.
put the income and children's figure in the tax calculation formula. if the totalTax <= 0, print "You owe no tax". if the total Tax > 0, print "you have to pay [tax amount] tax". END
I have tried to use the code bellow, but it doesn't work at all.
//Record user's income into double list "income"
double i;
//Record user's number of children into double list "kid"
double k;
//if...elif statement to calculate the toatal tax of the user
bool incomeOK = false;
bool kidOK = false;
do
{
Console.Write("What is your total income : ");
incomeOK = double.TryParse(Console.ReadLine(), out i);
if (!incomeOK || i < 0)
{
if (!incomeOK)
{
Console.WriteLine("Enter your income as a whole-dollar numeric figure.");
}
else if (i < 0)
{
Console.WriteLine("Your income cannot be negative.");
}
}
else
{
Console.Write("How many children do you have: ");
kidOK = double.TryParse(Console.ReadLine(), out k);
while (!kidOK || k < 0)
{
Console.Write("How many children do you have: ");
kidOK = double.TryParse(Console.ReadLine(), out k);
if (kidOK && k >= 0)
{
//Calculate the total payable tax of the user
double totalTax = (i - 10000 - (k * 2000)) * 0.02;
if (totalTax <= 10000)
{
Console.WriteLine("You owe no tax.");
Console.WriteLine("\n\n Hit Enter to exit.");
Console.ReadLine();
}
else
{
Console.WriteLine("You owe a total of $ " + totalTax + " tax.");
Console.WriteLine("\n\n Hit Enter to exit.");
Console.ReadLine();
}
}
if (!kidOK || k < 0)
{
if (!kidOK)
{
Console.WriteLine("You must enter a valid number.");
}
else if (k < 0)
{
Console.WriteLine("You must enter a positive number.");
}
}
}
}
}
while (!incomeOK || !kidOK);
but the OUTPUT:
What is your total income : sfd
Enter your income as a whole-dollar numeric figure.
Press any key to continue...
You need to split it up into sections.
First: Get positive number
double i;
double k;
Console.Write("What is your total income : ");
while (!double.TryParse(Console.ReadLine(), out i) || i < 0)
{
if (i < 0)
{
Console.WriteLine("Your income cannot be negative.");
}
else
{
Console.WriteLine("Enter your income as a whole-dollar numeric figure.");
}
}
Second: Get number of children
Console.Write("How many children do you have: ");
while (!double.TryParse(Console.ReadLine(), out k) || k < 0)
{
if (k < 0)
{
Console.WriteLine("You must enter a positive number.");
}
else
{
Console.WriteLine("You must enter a valid number.");
}
}
Third: Calculate
double totalTax = (i - 10000 - (k * 2000)) * 0.02;
if (totalTax <= 10000)
{
Console.WriteLine("You owe no tax.");
Console.WriteLine("\n\n Hit Enter to exit.");
Console.ReadLine();
}
else
{
Console.WriteLine("You owe a total of $ " + totalTax + " tax.");
Console.WriteLine("\n\n Hit Enter to exit.");
Console.ReadLine();
}
Whenever you get a wrong input, the while loop forces you to stay inside. When you get out, you can be sure the input is correct.
PS: I would use int for number of children, because it doesn't make any sense that you would have 2.3 children.
In your code, you aren't looping when it successfully parses but is a negative number.
Since your two loops are basically independent of each other, I wouldn't wrap them together in a loop (unless you intend on asking multiple times, but then that's simply another loop to repeat outside). Keep it simple and its easier to see the error. I changed it to this:
do
{
Console.Write("What is your total income : ");
incomeOK = double.TryParse(Console.ReadLine(), out i);
if (!incomeOK)
{
Console.WriteLine("Enter your income as a whole-dollar numeric figure.");
continue;
}
if (i < 0)
{
Console.WriteLine("Your income cannot be negative.");
incomeOK = false; // You need to manually set this to false to indicate it is not ok for it to loop.
}
} while (!incomeOk)
do
{
Console.Write("How many children do you have: ");
kidOK = double.TryParse(Console.ReadLine(), out k);
if (!kidOK)
{
Console.WriteLine("You must enter a valid number.");
continue;
}
if(k < 0)
{
Console.WriteLine("You must enter a positive number.");
kidOK = false; // Same deal as before
continue;
}
/// ... Your calculations
} while (!kidOK);
The code is now in two loops, your inputs for income, and inputs for children. Also, there's really no need to check if it's (!incomeOK || i < 0) first. If it's not ok, you output your message and loop. If it's negative, output your message, and make sure it loops. Otherwise just proceed with normal.

system.formatexception in while(true) loop

The subject is a little problem:
Write a program and continuously ask the user to enter a number or "ok" to exit. Calculate the sum of all the previously entered numbers and display it on the console.
Here is my code:
var sum = 0;
while (true)
{
Console.WriteLine("Enter a number or ok to exit:");
if (Console.ReadLine() == "ok") break;
sum += Convert.ToInt32(Console.ReadLine());
Console.WriteLine(sum);
}
When I tap ok, it terminate.
When I tap number and enter, it shows system.formatexception:The input string is not in the correct format.
I know one of the solution is
var sum = 0;
while (true)
{
Console.Write("Enter a number (or 'ok' to exit): ");
var input = Console.ReadLine();
if (input.ToLower() == "ok")
break;
sum += Convert.ToInt32(input);
}
Console.WriteLine("Sum of all numbers is: " + sum);
Maybe My code looks a little weired, But Why is my code wrong?
Reason is input will be "ok". Can not convert that into an integer.
first you have to store the first input value into other variable.
then convert that string into integer and get summation.
var sum = 0;
while (true)
{
Console.Write("Enter a number (or 'ok' to exit): ");
var input = Console.ReadLine();
int newVariable = 0;
if (input.ToLower() != "ok")
{
newVariable = Convert.ToInt32(input);
}
input = Console.ReadLine();
if (input.ToLower() == "ok"){
break;
sum += newVariable;
}
}
Console.WriteLine("Sum of all numbers is: " + sum);
If there any problem here please let me know.
Try this:
var sum = 0;
while (true)
{
Console.WriteLine("Enter a number or ok to exit:");
String ans = Console.ReadLine();
if (ans == "ok" || ans.ToLower() == "ok") break;
sum += Convert.ToInt32(ans);
Console.WriteLine(sum);
}
Here I've just store input entered by user in one variable and use that variable in further process.
In your first code you have take input two times, first one is in IF condition and second in parsing, that may cause the problem.
The correct way to do this is to use int.TryParse for your conversion from a string to a number. TryParse attempts to convert the string to a number, but if it cannot do so (for example, the string contains more than just numeric digits) it will fail gracefully instead of causing an exception. The other answers so far will all cause an unhandled FormatException if something non-numeric is entered other than "ok". By using int.TryParse you can handle the case where it's a valid number, as well as the case where it is invalid, and then alert the user. Here's an example within the context of your code:
// I prefer using concrete types for numbers like this, so if anyone else
// reads it they know the exact type and numeric limits of that type.
int sum = 0;
int enteredNumber = 0;
while (true)
{
Console.Write("Enter a number (or 'ok' to exit): ");
var consoleInput = Console.ReadLine();
if (consoleInput.ToLower() == "ok")
break;
if(int.TryParse(consoleInput, out enteredNumber))
{
sum += enteredNumber;
}
else
{
Console.WriteLine("You entered '" + consoleInput + "', which is not a number.");
}
}
Console.WriteLine("Sum of all numbers is: " + sum.ToString());
This is better because you know you have no control over the user's input other than to validate it yourself, and so it's better to speculatively convert the number and be alerted to success or failure without triggering an exception. Wrapping everything with a try/catch block is not a proper solution.
Your first code example, as rightly pointed out in the comments, reads a line, tests it for 'ok', then throws it away, reads another line, and uses that to add to the sum, which is not what you wanted.
After some quick research, I would say the most concise way to handle this in C# is probably something like your second code example. In F# I was able to come up with the following examples (one is a loop, the other uses sequences, i.e. IEnumerable<_>s) but I found no concise way to get the same with C# and LINQ…
let inputLoop () =
let rec aux sum =
match stdin.ReadLine () with
| "ok" -> sum
| s -> aux (sum + int s)
stdout.WriteLine (aux 0 |> string)
let inputSeq () =
fun _ -> stdin.ReadLine ()
|> Seq.initInfinite
|> Seq.takeWhile (fun s -> s <> "ok")
|> Seq.sumBy int
|> string
|> stdout.WriteLine
Try it :)
var sum = 0;
while (true)
{
Console.Write("Enter a number: or ok to exit : ");
String input = Console.ReadLine();
if (input == "ok" || input.ToLower() == "ok") break;
if(string.IsNullOrWhiteSpace(input))
continue;
sum += Convert.ToInt32(input);
}
Console.WriteLine("Total Result: " + sum);
Write a program and continuously ask the user to enter a number or "ok" to exit. Calculate the sum of all the previously entered numbers and display it on the console. Happy Coding
var sum = 0;
while (true)
{
Console.Write("Write number or write \"ok\" for exit: ");
var input = Console.ReadLine();
if (input.ToLower() != "ok")
{
sum += Convert.ToInt32(input);
continue;
}
break;
}
Console.WriteLine("All sum: " + sum + ".");
This is one way to do it. I'm just learning to do this!
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Enter number to know the sum or press ok to exit and display the sum");
int sum = 0;
while (true) // to run the program continously asking user input
{
Console.WriteLine("Enter Number: ");
var input = Console.ReadLine(); // takes user input
if (input.ToLower() == "ok") // compares user input to string ok
break; //if user input is ok, breaks the loop and sum is displayed
var inputInInt = Convert.ToInt32(input); // if user input is int, continues to convert it to integer
sum += inputInInt; // user input in interger is added to sum
}
Console.WriteLine("The sum of entered numbers is: " + sum);
Console.ReadLine();
}
}

Guessing Game Number Issue

Before I get down-voted for the extensive code, I feel it's necessary for a solution to present itself.
I've made alterations to the program's code from the help previously presented, but I still seem to be falling into the problem that the random number number is either not being properly compared (I've had examples where number is '5' and the user's guess is '5', but I'm still getting a comment that "You're quite far off! Try again." meaning it's falling into else if (userinputcalc > 4 | userinputcalc < 10)...
So, at this stage the issue seems to lie within the comparison of number and the userinput, leading to confusing output messages.
I'm probably missing something obvious here, despite being sure it's around the loop of comparing number and userinput but I've been looking at this code and seeing nothing.
Any help is greatly appreciated, as always.
public void GuessingGame()
{
string username; // Will be the user's chosen name for program interaction
int guessesleft = 0;// Stands for the number of guesses left (out of 3)
int spaceaway = 0; // Space from the guess and the random number, if not correct guess
int roundcount = 1; //Started at 1 for the sake of the user interface - aesthetics
int number = 0; // Current value of the random number
int userinput = 0; //User input is the guess the user makes during the guessing game
int userinputcalc = 0;// calculation of guess and random number, when added to spaceaway calculation
int answersright = 0; // Number of times the user guessed the number correctly
Random rndm = new Random(); // Initialises a new class of random, which'll be used to simulate the random number
Console.WriteLine("Welcome to Guessing Game!");
Console.WriteLine("");
Console.WriteLine("Please press any button to continue.");
Console.ReadLine();
Console.WriteLine("What's your name?");
username = (Console.ReadLine());
//If you're wondering at all, the "You must guess what it is inthree tries." is intentional, since it was showing double-spaced in the command prompt
Console.WriteLine("Well, " + username + ", I am thinking of a number from 1 to 10. You must guess what it is inthree tries.");
Console.WriteLine("");
{
do
{
Console.WriteLine("Round" + roundcount); //Displays the which round (out of 10) to the user
guessesleft = 3; //The remaining guesses left for the user
do
{
number = rndm.Next(10) + 1; // int number is set to a random number between 1 and 10
Console.WriteLine("Please enter a guess:");
userinput = int.Parse(Console.ReadLine());
guessesleft = guessesleft - 1;
if (userinput == number)
{
//Below, once you've guessed right, you will have this message displayed in the console
Console.WriteLine("You guessed " + number + " *RIGHT*!");
answersright = answersright + 1;
guessesleft = 0;// No point need to guess further on something you've guessed correctly - saves correct answer value exploit
}
else if (userinput < 1 || userinput > 10) // If user's guess is less than 1 or more than 10, then out of range. Counts as a guess.
{
Console.WriteLine("You guessed " + userinput + "! and it was incorrect!");
Console.WriteLine("This is outside of the range of numbers between 1-10 ");
}
else if (userinput != number) // while the user's guess does not equal the number
{
{
// userinputcalc = Math.Abs(number - userinput);
//Left out as I was getting abnormal run-time outputs and the math showed up wrong.
//(Example: RND No. = 5 Userinput = 5 Output: "Incorrect" "Hot")
spaceaway = (number - userinput); // Works out how far from the random no. the user's guess is.
// If user guesses 6 and random no. is 5, answer will be -1 this makes the value +ve and allows output to be shown without error
if (spaceaway < 0)
{
spaceaway = (spaceaway * -1);
userinputcalc = spaceaway;
}
else if (spaceaway > 0)
{
userinputcalc = spaceaway;
}
}
{
if (userinputcalc < 2)
{
Console.WriteLine("You guessed " + userinput + "! and it was wrong!");
Console.WriteLine("Hot");
}
else if
(userinputcalc < 3)
{
Console.WriteLine("You guessed " + userinput + "! and it was wrong!");
Console.WriteLine("Warm");
}
else if
(userinputcalc < 4)
{
Console.WriteLine("You guessed " + userinput + "! and it was wrong!");
Console.WriteLine("Cold");
}
else if (userinputcalc > 4 | userinputcalc < 10)
{
Console.WriteLine("You guessed " + userinput + "! and it was wrong!");
Console.WriteLine("You're quite far off! Try again.");
}
}
}
} while (guessesleft > 0);
Console.WriteLine("");
Console.WriteLine("The number was, "+number+"!");
Console.WriteLine("");
roundcount = roundcount + 1;
} while (roundcount < 11);
Console.WriteLine("Well, " + username + ". " + "You guessed correctly, " + answersright + " times!");
}
}
}
}
OK I think theres quite a few issues here (some are off topic but definitely worth mentioning)..
I wouldn't advise using while loops to check for specific inputs
For example:
Instead of roundCount != 11 use roundCount < 11
Then there is less chance of forever getting stuck in a loop
You should declare Random outside of your loops otherwise you run the risk of just getting the same numbers ("randomly")
You reset the number to a new number after every guess so the user doesn't have a chance to guess the right number
With all this being said, I think the Math.Abs was correct if you are trying to find the distance away from the number.. I wouldnt use less than two though as that would mean only numbers that are 1 away from the answer are "hot"
Note: Answer is based off question revision #5
Update
Doesn't seem like you were far off but you still reset the number every loop
number = rndm.Next(10) + 1; //Insert here
do
{
//Displays the which round (out of 10) to the user
Console.WriteLine("Round" + roundcount);
guessesleft = 3; //The remaining guesses left for the user
do
{
// Remove this -- number = rndm.Next(10) + 1;
I think this is what you want,please try it:
static int guessesleft;
static Random ran = new Random();
static int MagicNumber;
static string UserInput;
static void Main(string[] args)
{
ConsoleKeyInfo ci = new ConsoleKeyInfo();
do
{
guessesleft = 3;
UserInput = "";
Console.Clear();
string username;
int guesscount = 1;
Console.WriteLine("Welcome to Jackie's Guessing Game!");
Console.WriteLine("");
Console.WriteLine("Please press any button to continue.");
Console.ReadLine();
Console.WriteLine("What's your name?");
username = (Console.ReadLine());
//If you're wondering at all, the "You must guess what it is inthree tries." is intentional, since it was showing double-spaced in the command prompt
Console.WriteLine("Well, " + username + ", I am thinking of a number from 1 to 10. You must guess what it is inthree tries.");
Console.WriteLine("");
MagicNumber = ran.Next(1, 11);
do
{
Console.WriteLine("Please insert your " + guesscount++ + "º guess!");
UserInput = Console.ReadLine().Trim();
if (UserInput == MagicNumber.ToString())
break;
if (Math.Abs(Convert.ToInt32(UserInput) - MagicNumber) < 2)
Console.WriteLine("Hot!!");
else if(Math.Abs(Convert.ToInt32(UserInput) - MagicNumber) < 3)
Console.WriteLine("Warm!!");
Console.WriteLine("No luck , you have " + --guessesleft + "º guesses left!");
Console.WriteLine();
} while (guesscount < 4);
if (guesscount == 4)
Console.WriteLine("Sorry " + username + " no more tries,you lost!");
else
Console.WriteLine("Congratulations your guess with number " + UserInput + " is correct,the number was " + MagicNumber);
Console.WriteLine("Press Q to quit or Enter to Play again!");
ci = Console.ReadKey();
} while (ci.Key != ConsoleKey.Q);
}

C# User input needs to be >= 2, but how to make it so?

This part is hard for me for some reason. Everything else works nicely, but I can't seem to figure out how to make it to where it re-asks the question if the input is >=2...
if (minimumSides >= 2)
I get this part, but it hates minimumsides >= 2.
do
{
Console.Write("Enter minimum number of sides >2: ");
int.TryParse(inputminside, out minimumSides);
if (minimumSides >= 2)
Console.Write("Enter minimum number of sides >2: ");
else
inputminside = Console.ReadLine();
}
while (!int.TryParse(inputminside, out minimumSides));
You are almost there:
do {
Console.Write("Enter minimum number of sides >2: ");
inputminside = Console.ReadLine();
} while (!int.TryParse(inputminside, out minimumSides) || minimumSides < 2);
Could the problem be that during the first iteration of the loop "inputminside" has not been initialized?
This is one way you could do it:
var minimumSides = 0;
while (minimumSides <=2)
{
Console.Write("Enter minimum number of sides >2: ");
int.TryParse(Console.ReadLine(), out minimumSides);
}
// carry on with your code here...
This is what you want -
do
{
Console.Write("Enter minimum number of sides >2: ");
inputminside = Console.ReadLine();
}
while (!int.TryParse(inputminside, out minimumSides) && minimumSides < 2);

Categories

Resources