Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
Write a program that will continue to prompt the user to guess a number until the correct number has
been entered. You should also consider user validation; that is, has the user entered a number less than
1 or greater than 10? Have they entered a character? Start by creating a new project and name its main
class (and file) as GuessingNumber. Then proceed with the following steps:
Create an integer variable called number and set it equal to 5.
Prompt the user to guess a number between 1 and 10.
If the user enters number 5, print “You have guessed the number! Well done!”
If they do not enter 5, continue to prompt the user to enter a number until they enter 5.
Here is my code so far
using System;
namespace Progam
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Guess a number between 1 and 10");
int number = Convert.ToInt32(Console.ReadLine());
if (number < 1 || number > 10)
{
Console.WriteLine("This is out of the range");
}
if (number == 5)
{
Console.WriteLine("you have guessed the correct number");
}
}
}
}
How would I write the code to prompt the user to guess again if the number is not equal to 5?
Thanks
Here is your code slightly modified. There are many other ways to do this, this is one and a bit more readable for newer programmers.
bool Correct = false;
while (!Correct)
{
int number = Convert.ToInt32(Console.ReadLine());
if (number < 1 || number > 10)
{
Console.WriteLine("This is out of the range");
}
if (number == 5)
{
Console.WriteLine("you have guessed the correct number");
Correct = true;
}
}
static void Main(string[] args)
{
var ok = false;
do
{
Console.WriteLine("Guess a number between 1 and 10");
if (!int.TryParse(Console.ReadLine(), out var number))
{
Console.WriteLine("Not a number");
continue;
}
if (1 > number || number > 10)
{
Console.WriteLine("This is out of the range");
continue;
}
ok = number == 5;
if (ok)
{
Console.WriteLine("you have guessed the correct number");
}
} while (!ok);
Sure hope I get a good grade!
do
{
var number = Convert.ToInt32(Console.ReadLine());
....
}while(number != 5)
Related
So I wrote a lottery program.
The program works as the following:
the user inputs 6 numbers ranging from 1 to 46.
the program chooses 6 numbers ranging from 1 to 46.
the program compares the arrays for matching numbers.
the program shows the user how many matching number he got right and also if he won the lottery or not.
end
now , I want to add an option to the user , if the user wants to try again he can just press Y and the program will jump him to the point where he inputs numbers.
But , I don't know how to achieve that without using goto, I don't want to use goto because I know it's bad practice to use it.
Would love to get some recommendations.
I know that I am still missing the N portion of the code, but I just wanted to show what I've tried so far.
char tryAgain;
if (gamelost || gamewon == true)
{
tryAgain = 'Y';
Console.WriteLine("Do you want to try again? Y/N");
tryAgain = char.Parse(Console.ReadLine());
if (tryAgain == 'Y')
{
goto gameAgain;
}
else
{
return;
}
}
}
Use a loop. You need to check the only condition upon which you exit the loop. Note that this code doesn't sanitize user's input.
using static System.Console;
void do_lottery()
{
while (true)
{
Write("Enter 6 digits, divided by comma: ");
var input = ReadLine();
var user_numbers = input.Split(",").Select(n => int.Parse(n));
var numbers_to_guess = new[] { 6, 23, 12, 46, 8, 2 };
if (user_numbers.All(n => numbers_to_guess.Any(z => z == n)))
{
WriteLine("You won!");
}
else
{
WriteLine("You lose!");
}
Write("Do you wanna play once again? (Y/N): ");
var answer = ReadLine().ToUpper();
if (answer != "Y") break; //Exit loop
}
WriteLine("Lottery finished.");
}
This question already has answers here:
How do I only allow number input into my C# Console Application?
(7 answers)
Closed 5 years ago.
I want the program to continue on running after a user enters an invalid input. When a user inputs a string, an error message displays and then the program closes, however I want the program to continue asking the user to enter a valid input. I tried put the try/catch inside the do/while but it doesn't seem to work for me.
Int16 dollars;
try
{
do
{
Console.WriteLine("Enter a value, or 0 to exit.");
dollars = Convert.ToInt16(Console.ReadLine());
if (dollars >= 1)
{
Console.WriteLine("your current balance is");
myBank.addMoney(dollars);
myBank.getValue();
}
else if (dollars < 0)
{
Console.WriteLine("You have entered a negative number, your current balance is");
myBank.getMoney(dollars);
myBank.getValue();
}
} while (dollars != 0);
}
catch
{
Console.WriteLine("The value you have entered is invalid");
Console.ReadKey();
}
Instead of converting the input, use TryParse.
Console.WriteLine("Enter a value, or 0 to exit.");
var input = Console.ReadLine();
var ok = Int16.TryParse(input, out dollars);
if (!ok)
{
Console.WriteLine("Please input a valid number.");
continue;
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
i solved an assignment question on my own but i seems not to be able to print an else statement successfully even though the code works.
The questions is below,
Create a program that prompts the user for the first number. Show on the screen which number was chosen and if the
Number is greater than 10 then show your predecessors until you reach number 10.
My solution is below,
Console.WriteLine("Enter interger please: ");
int num = int.Parse(Console.ReadLine());
Console.WriteLine();
for (int num3 = num; 10 <= num3; num3-- )
{
if (num > 10)
{
Console.WriteLine(num3);
}
else
{
Console.WriteLine("The integer entered is less than zero and cannot be used in code ");
}
Well it's normal that in doesn't enter the else statement. You're doing if (num > 10) and num is the value entered by the user which never changes during the process. So if num = 15 you're always doing is 15 > 10.
Then only moment the else statement is gonna print is if the number entered is 10.
And the moment num is smaller than 10, you'll never get in the for loop so the number will never be smaller than 0 inside the loop so that line won't make sense even if it's played
Console.WriteLine("The integer entered is less than zero and cannot be used in code ");
Cause like i said if this line is printed that means the value in num was 10 which is not less than zero.
You could change it for something like this
if(num < 10)
{
Console.WriteLine("It's smaller than 10");
}
for(int num3 = num; 10 <= num3; num3--)
{
Console.WriteLine(num3);
}
You're decrementing "num3" on the for loop, but you're validating if "num" is greater than 10 which, by entering the loop in the first place, will always be true.
Change to:
if (num3 > 10)
{
Console.WriteLine(num3);
}
Are you able to provide the question?
The code you have written seems a little meaningless.
Firstly, the for loop will only run if you enter an integer >= 10
Rewriting your code:
Console.WriteLine("Please enter a positive integer: ");
var args = Console.ReadLine();
if (int.TryParse(args, out int num))
{
if (num < 0)
Console.WriteLine('Must enter a positive integer!');
for (var i = num; i >= 10; i-- )
{
//this only runs if the integer entered is >= 10
if (num > 10)
{
Console.WriteLine(i);
}
}
}
else
{
Console.WriteLine("A non-integer was entered!");
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
this is my program I hope you understand what I am trying to do.
if (primeNum = int)
{
Console.WriteLine(" the number entered is not prime ");
}
If you want to know if it's a whole number, then round it and compare the numbers. If the number is a whole number, it will not change when it's rounded...so if the rounded version of the number is equal to the number itself, then it's a whole number. If they're different, then it's not a whole number:
double i = 1.2;
if (Math.Round(i, 0, MidpointRounding.AwayFromZero) == i) {
//whole number
} else {
//not a whole number
}
private static bool IsWhole(double number)
{
return (number % 1 == 0);
}
If Program.isWhole(5.67) returns true call System.Environment.Exit(0) to close application.
Try this program:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace primeCsharp
{
class Program
{
static void Main(string[] args)
{
int n = 0; // Number to be test for prime-ness
int i = 2; // Loop counter
bool is_prime = true; // Boolean flag...
// Assume true for now
Console.WriteLine("Enter a number and press ENTER: ");
n = Console.Read();
// Test for a prime number by checking for divisiblity
// by all whole numbers from 2 to sqrt(n).
while (i <= Math.Sqrt(n))
{
if (n % i == 0)
{ // If i divides n,
is_prime = false; // n ix not prime
break; // BREAK OUT OF THE LOOP NOW!
}
++i;
}
// Print results
if (is_prime)
{
Console.WriteLine("Number is prime.\n");
}
else
{
Console.WriteLine("Number is not prime.\n");
}
}
}
}
See this:
How can I get the data type of a variable in C#?
and try:
if(primeNum.GetType() == typeof(int))
You can check whether the number is equal to the value of its conversion to int, like this:
if (primeNum == (int)primeNum)
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 8 years ago.
Improve this question
I have written up to this place and am stuck I need help on how to terminate a program or continue .
What I mean is that when I ask the question would you like to withdraw today and if their response is NO then the program should terminate but if its YES it should continue.
What am I missing?
Please implement the aspect where by the program should terminate using the N for NO statement i didn't received the answer to that.
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
int amount = 20000;
int choice, pin = 0, x = 0;
Console.WriteLine("Enter your pin");
pin = int.Parse(Console.ReadLine());
Console.WriteLine("welcome to HSPUIC bank would you like to make a withdraw today N or Y");
Console.ReadLine();
}
}
}
You are on the right track. What you are missing is to take and evaluate the user input - this is the information returned by the Console.ReadLine method (as mentioned in the comments) like this:
line = Console.ReadLine();
Your code could look like this:
int amount = 20000;
int choice, pin = 0, x = 0;
Console.WriteLine("Enter your pin");
pin = int.Parse(Console.ReadLine());
Console.WriteLine("welcome to HSPUIC bank would you like to make a withdraw today N or Y");
// save user input
var userInput = Console.ReadLine();
// evaluate if user wants to continue or not
if (userInput.ToLower() == "y")
{
// if yes, go further
Console.WriteLine("continue with other action...");
}
// else bye
Console.WriteLine("goodbye");
The line for the PIN already uses the user input! The same can be done with the question. If you want to stay in the loop until the user does not want to withdraw any more, than you need more than if-else. Take a look at the iteration statements like do and while.
A solution could look like this:
// user input = y or n
string choice;
// user pin
int pin = 0;
// state that indicates if the user wants to continue or not
bool continueLoop = false;
do
{
// greet user
Console.WriteLine("welcome to HSPUIC bank would you like to make a withdraw today N or Y");
// take input
choice = Console.ReadLine();
// check if user has entered valid input
if (choice.ToLower() == "y" || choice.ToLower() == "n")
{
// default decision is "user does not want to continue" = exit
continueLoop = false;
// user has choosen to continue
if (choice.ToLower() == "y")
{
// user wants to do something, so stay in the loop
continueLoop = true;
// ask for pin
Console.WriteLine("Enter your pin");
var pinAsText = Console.ReadLine();
// convert the pin to number: if (int.TryParse(pinAsText, out pin)) ...
if (pinAsText == "1234")
{
Console.WriteLine("PIN correct");
// continue with logic here, for example take amount
}
else
{
Console.WriteLine("PIN incorrect");
}
}
}
else
{
Console.WriteLine("Please enter Y or N");
continueLoop = true;
}
} while (continueLoop);
Console.WriteLine("goodbye");
Now the flow looks like this:
welcome to HSPUIC bank would you like to make a withdraw today N or Y
>> Y
Enter your pin
>> 3
PIN incorrect
welcome to HSPUIC bank would you like to make a withdraw today N or Y
>> Y
Enter your pin
>> 1234
PIN correct
welcome to HSPUIC bank would you like to make a withdraw today N or Y
>> N
goodbye
Certainly when your users have two different choice , you should use if in your program . Also you should save user's answer into a local variable to process it .
static void Main(string[] args)
{
int amount = 20000;
int choice, pin = 0, x = 0;
Console.WriteLine("Enter your pin");
pin = int.Parse(Console.ReadLine());
Console.WriteLine("welcome to HSPUIC bank would you like to make a withdraw today N or Y");
char answer = char.Parse(Console.ReadLine());
if (answer == 'Y')
{
//Code that must be executed after choosing "yes" .
Console.ReadKey();
}
}
When you write nothing for "no" , your program will terminate .
Also you can use string instead of char :
string answer = Console.ReadLine();
if (answer == "Y")
{
//Code that must be executed after choosing "yes" .
Console.ReadKey();
}
By the way, there are a lot of possible errors in your code (e.g. enter a character instead of integer for variable ' pin ') that must be handled by try-catch.