Lets say for a console application, I want the user to enter how many dices he would like to throw. Onlu values 1-5 will be accepted. I tried doing this:
Console.WriteLine("How many dices would you like to throw?");
int amount = Convert.ToInt32(Console.ReadLine());
while(true)
{
if(amount < 1 || amount > 5)
{
Console.WriteLine("Please enter a value between 1-5");
break;
}
}
The problem here is that if the user enters an invalid number, the program stops. I want it to simply continue asking until correct value is inputed. Any ideas?
cheers.
I haven't tested it but slightly refactored your code as below, it should do what you want:
Console.WriteLine("How many dices would you like to throw?");
int amount = Convert.ToInt32(Console.ReadLine());
while(amount < 1 || amount > 5)
{
Console.WriteLine("Please enter a value between 1-5");
amount = Convert.ToInt32(Console.ReadLine());
}
EDIT: if you want to safely check whether it is an integer value, you can use the below version of code:
Console.WriteLine("How many dices would you like to throw?");
var input = Console.ReadLine();
while(!int.TryParse(input, out int amount) || amount < 1 || amount > 5)
{
Console.WriteLine("Please enter a value between 1-5");
input = Console.ReadLine();
}
You might want to check if the entered value is actually an integer.
int amount;
Console.WriteLine("How many dices would you like to throw?");
do
{
if (int.TryParse(Console.ReadLine(), out var i))
{
if (i >= 1 && i <= 5)
{
amount = i;
break;
}
Console.WriteLine("The integer value is not between 1 and 5");
}
{
Console.WriteLine("The value you entered is not an integer");
}
} while (true);
EDIT
I generally like to give the user the option to exit completely.
int amount;
Console.WriteLine("How many dices would you like to throw? Or enter 'X' to exit.");
do
{
var input = Console.ReadLine();
if(input.Equals("X", StringComparison.InvariantCultureIgnoreCase))
{
return;
}
if (int.TryParse(input, out var i))
{
if (i >= 1 && i <= 5)
{
amount = i;
break;
}
Console.WriteLine("The integer value is not between 1 and 5");
}
{
Console.WriteLine("The value you entered is not an integer");
}
} while (true);
Related
I am currently working on a program that is a loop with a sentinel value that asks the user to enter a number or enter -99 to end the program and it runs perfectly. If I were to change that -99 to just the word "Quit" is there a certain parameter that I would have to put? For example, if I want to use a letter, I know that I could use:
char (undefined parameter) = 'A'
But how would I do this with a word? When I simply try to change the value of -99 to Quit, I receive an error as expected.
using System;
class Program {
public static void Main (string[] args) {
int sum = 0;
int counter = 0;
int max = Int32.MinValue;
int min = Int32.MaxValue;
bool keepGoing = true;
while(keepGoing) {
Console.WriteLine("Please enter a number or enter -99 to stop the program:");
int number = Convert.ToInt32(Console.ReadLine());
if (number == -99){
keepGoing = false;
} else {
counter++;
sum += number;
if (number >= max) {
max = number;
}
if (number <= min) {
min = number;
}
}
}
double average = (double) sum / counter;
Console.WriteLine($"{counter} numbers were entered.");
Console.WriteLine("The average is:" + average);
Console.WriteLine("The sum is:" + sum);
Console.WriteLine("The maximum value is:" + max);
Console.WriteLine("The minimum value is:" + min);
}
}
It's difficult to store "Quit" in an int, so the root of your problem is that you have no separation between pulling the string from the console and converting it to an int:
int number = Convert.ToInt32(Console.ReadLine());
if (number == -99){
keepGoing = false;
} else {
counter++;
If you did have a separation, it becomes possible:
string input = Console.ReadLine();
if (input == "Quit"){
keepGoing = false;
} else {
int number = Convert.ToInt32(input);
counter++;
I am writing a C# program that prints "true" if number <= 20 and "false" if number > 20 using a while loop but the program keeps on executing.
I want to break the program if it reaches certain number e.g. number > 26.
The code for the program is:
public static void Main()
{
Console.WriteLine("Please enter a number");
int numnber = Convert.ToInt32(Console.ReadLine());
while (numnber <= 20)
{
Console.WriteLine("True");
Console.ReadLine();
int number1 = numnber++;
while (numnber > 20)
{
Console.WriteLine("False");
Console.ReadLine();
}
}
}
you can just use break; Try this:
Console.WriteLine("Please enter a number");
int numnber = Convert.ToInt32(Console.ReadLine());
while (numnber <= 20)
{
Console.WriteLine("True");
Console.ReadLine();
int number1 = numnber++;
while (numnber > 20)
{
Console.WriteLine("False");
Console.ReadLine();
}
break;
}
But this programming is not good at all because you are breaking loop after all for this simply you can use if else like this..
Console.WriteLine("Please enter a number");
int numnber = Convert.ToInt32(Console.ReadLine());
if(numnber <= 20)
{
Console.WriteLine("True");
}
else
{
Console.WriteLine("False");
}
According to your description, your major issue should be
the program keeps on executing
However, it's not going to reach 26 as #King King mentioned.
It stuck inside the inner while which should be replaced by if condition.
Lastly, if you have to exec the number check at least one time you can use do while
do
{
if (numnber <= 20)
{
Console.WriteLine("True");
}
else if (numnber > 20)
{
Console.WriteLine("False");
}
numnber++;
Console.WriteLine("number: {0}", numnber);
} while (numnber < 26);
Console.ReadLine();
Thank you all but the solution to the problem would be. The code is as follows:
public static void Main()
{
int number;
do
{
Console.WriteLine("Please enter a number");
number = Convert.ToInt32(Console.ReadLine());
do
{
Console.WriteLine("True value. True value is supplied");
Console.ReadLine();
number++;
while (number >= 21 && number < 27)
{
Console.WriteLine("False value. False value is supplied");
Console.ReadLine();
number++;
}
} while (number <= 20);
} while (number > 27);
}
I have this code where I input a name, and then an integer. The application will then repeat the name entered according to the integer specified. The issue i'm having is, I only want the user to be able to repeat the name a max of 10 times and and min of 1. Here is what i have thus far.
Console.Write("PLEASE ENTER YOUR FIRST AND LAST NAME: ");
string Name = Console.ReadLine();
Console.Write("Enter the number of times you wish for me to repeat your name, " + Name );
int number = Int32.Parse(Console.ReadLine());
for (int i = 0; i < number; i++)
Console.WriteLine(""+ Name);
Console.ReadKey();
EDIT: If someone sees an easier way of doing what I have, I would be happy to suggestions!
You need to filter and validate if the input number is minimum of 1, and maximum of 10, before printing the names. You can do this:
Console.Write("PLEASE ENTER YOUR FIRST AND LAST NAME: ");
string Name = Console.ReadLine();
Console.Write("Enter the number of times you wish for me to repeat your name, " + Name);
int number = 0;
do
{
Int32.TryParse(Console.ReadLine(), out number);
if (number > 10 || number < 1)
Console.WriteLine("Please input numbers between 1 to 10");
} while (number > 10 || number < 1);
for (int i = 0; i < number; i++)
Console.WriteLine("" + Name);
Console.ReadKey();
I am doing a do-while loop here. Unless the while loop is satisfied, it will continuously verify if the number is on the range specified or else it will exit and it will print the names.
static void Main(string[] args)
{
Console.Write("PLEASE ENTER YOUR FIRST AND LAST NAME: ");
string Name = Console.ReadLine();
Console.Write("Enter the number of times you wish for me to repeat your name");
var input = Console.ReadLine();
int number = -1;
while (!int.TryParse(input, out number)) {
Console.WriteLine("Incorrect Value");
Console.Write("Enter the number of times you wish for me to repeat your name");
input = Console.ReadLine();
}
for (int i = 0; i < number; i++)
{
Console.WriteLine("" + Name);
if (i == 9)
{
Console.WriteLine("End Program");
break;
}
}
Console.ReadKey();
}
You could wrap the ReadLine() in a while statement
Example being
int number = -1;
while(number < 1 || number > 10)
{
//Input code
}
//for loop goes under here
I'm on my first week of studying C#.
I guess there should be some way to use 1 "While()" condition instead of 2 in the code below. Is there any way to make my code more simple:
/* ask the user to guess a number.
any number between 10 and 20 is the RIGHT choice,
any other number outside of that scope is WRONG. */
int num;
Console.WriteLine("[Q] Quit or make your choice");
string answer = Console.ReadLine();
if (answer == "Q" || answer == "q")
Console.WriteLine();
else
{
num = Convert.ToInt32(answer);
while (num < 10)
{
Console.WriteLine("Wrong, try again");
num = Convert.ToInt32(Console.ReadLine());
}
while (num > 20)
{
Console.WriteLine("Wrong, try again");
num = Convert.ToInt32(Console.ReadLine());
}
Console.WriteLine("Your number is {0} and it's RIGHT", num);
Console.ReadKey();
}
You can use the OR operator to combine both conditions:
/* ask the user to guess a number.
any number between 10 and 20 is the RIGHT choice,
any other number outside of that scope is WRONG. */
int num;
Console.WriteLine("[Q] Quit or make your choice");
string answer = Console.ReadLine();
if (answer == "Q" || answer == "q")
Console.WriteLine();
else
{
num = Convert.ToInt32(answer);
while (num < 10 || num > 20)
{
Console.WriteLine("Wrong, try again");
num = Convert.ToInt32(Console.ReadLine());
}
Console.WriteLine("Your number is {0} and it's RIGHT", num);
Console.ReadKey();
}
I am new to programming and I think I have confused myself I'm trying to make a loop that asks users for integers when the user inputs a integer greater than 100 then the console displays the amount of integers the user has input and the sum of these integers. I know it's basic but I can't figure where I went wrong.
namespace Wip
{
class Program
{
static void Main(string[] args)
{
string strNum1, strNum2;
int num1, num2;
int i = 0;
int sum =0 ;
Console.WriteLine("Please enter a integer between 1 and 100"); // asks for user input
strNum1 = Console.ReadLine();
num1 = int.Parse(strNum1);
do //repeat asking for user input
{
Console.WriteLine("Please enter another integer between 1 and 100"); // asks for user input
strNum2 = Console.ReadLine();
num2 = int.Parse(strNum2); //input is stored as num2
sum = num2; //store num2 in sum
i++;
if (num2 >= 100) // if num2 int is greater than 100
{
sum = (num1 +num2 +sum); // do calculation
Console.WriteLine("No of integers entered is {0} {1}", i, sum); //output calculation
}
}
while (i < 100);
}
}
}
any help would be appreciated thanks everyone!
You're on the right track... a couple of things:
Do... While is used when you always want to run through the block at least once, so your first 'get' from the user can be inside the block. You can code whatever you want to happen after the condition fails right after the block, instead of checking the same condition inside it.
Make sure if you're simply using Parse that you wrap it in a try...catch, because your user could type in anything (not just numbers). Personally I usually use TryParse instead.
Finally, make sure you're comparing to the correct variable. Checking that i < 100 will keep looping until 100 numbers have been entered; you want to compare the user's input instead.
namespace Wip
{
class Program
{
static void Main(string[] args)
{
string prompt = "Please enter {0} integer between 1 and 100";
string strNum;
int num = 0;
int i = 0;
int sum =0 ;
do //ask once and repeat while 'while' condition is true
{
string pluralPrompt = i > 0 ? "another" : "an";
prompt = string.Format(prompt,pluralPrompt);
Console.WriteLine(prompt); // asks for user input
strNum = Console.ReadLine();
if (!Int32.TryParse(strNum, out num)) //input is stored as num
{
// warn the user, throw an exception, etc.
}
sum += num; //add num to sum
i++;
}
while (num < 100);
Console.WriteLine("No of integers entered is {0} {1}", i, sum); //output calculation
}
}
}
namespace Wip
{
class Program
{
static void Main(string[] args)
{
string strNum;
int num;
int i = 0;
int sum = 0;
do //repeat asking for user input
{
Console.WriteLine("Please enter another integer between 1 and 100"); // asks for user input
strNum = Console.ReadLine();
if (int.TryParse(strNum, out num)) //input is stored as num2
{
if (num < 101)
{
i++;
sum += num;
continue;
}
else
{
Console.WriteLine("No of integers entered is {0} {1}", i, sum); //output calculation
break;
}
}
}
while (i < 100);
}
}