Reask for User Entry or Continue the code [closed] - c#

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
Facing this problem all the time but couldn't really figure out how to overcome with it;
It is related with the user entry - in case the user enters something wrong I want the program to continue or reask the question;
an example ;
I want the user to enter the age
when the user enters the age correctly I want the program to continue (but in below code it asks 5 times
if the user enters a wrong entry (i.e string) I want the program to reask to enter the age
Vm appreciate to hearing your kind assitance
for (int i = 0; i < 5; i++)
{
int _Age;
Console.Write ("Please enter your age :")
string AgeEntry = Console.ReadLine();
bool AgeCheck = Int32.TryParse(AgeEntry, out _Age);
if (!AgeCheck)
{
Console.WriteLine("Please enter your age : ");
}
else
{
i--;
continue;
}
}

int age = 0;
while (true)
{
Console.WriteLine("Please enter your age:");
string entry = Console.ReadLine();
if (int.TryParse(entry, out age)) break;
}
The idea is simply to run an "infinite" loop until a valid age is entered, at which point we break out of the loop.

Instead of the infinite loops:
int age = 0;
do
{
Console.WriteLine("Please enter your age:");
string entry = Console.ReadLine();
} while (!int.TryParse(entry, out age));
Nothing wrong with the infinite loop inherently. I just think it's cleaner without.

infinite loop, just issue a "break;" and it will drop out....
int _Age;
while( true )
{
Console.Write ("Please enter your age :")
string AgeEntry = Console.ReadLine();
bool AgeCheck = Int32.TryParse(AgeEntry, out _Age);
if ( AgeCheck == true ) { break; }
}

Answer to your question about the question being asked 5 times. You have a for loop that will spin through the code 5 times regardless of the answer the user gives.
for (int i = 0; i < 5; i++)
{ your code is here }
In the code below, after the do loop, you'll have the input from the console in the answer variable and the parsed int in the age variable. You can create a new console app in VS and paste this into Program.cs and run it to test.
using System;
namespace console {
internal class Program {
private static void Main( string[] args ) {
int age;
string answer;
do {
Console.Clear();
Console.Write( "Please enter your age: " );
answer = Console.ReadLine();
} while ( !int.TryParse( answer, out age ) );
Console.WriteLine( string.Empty );
Console.WriteLine( "Thanks, let's continue..." );
Console.Read();
}
}
}

Related

if statements in while loops [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I am new to programming, and I am trying to practice various functions with a simple "Pick a Number" application. However I have ran into a problem.
Random rnd = new Random();
int deNumero = rnd.Next(1,100001);
while (true)
{
Console.WriteLine("Pick a number 1 - 100000");
string input = Console.ReadLine();
int numero = Int32.Parse(input);
if(numero < deNumero)
{
Console.WriteLine("Lower");
}
else if(numero > deNumero)
{
Console.WriteLine("Higher");
}
else if(numero == deNumero)
{
Console.WriteLine("Well done!");
Console.ReadKey();
}
else
{
Console.WriteLine("What?");
}
}
Let's say I pick a number that is greater than deNumero and it prints "Lower". Where I am seeing a problem is when I pick the number 1, it will print "Lower" again. it keeps going to the same if statement even when it shouldn't. What am I doing wrong?
All your code working correct you can see result, I print your DeNumero to see or put break point in you if statement to figure out what is heppening:
Random rnd = new Random();
int deNumero = rnd.Next(1, 100001);
while (true)
{
Console.WriteLine("DeNomero:{0}", deNumero);
Console.WriteLine("Pick a number 1 - 100000");
string input = Console.ReadLine();
int numero = Int32.Parse(input);
if (numero < deNumero)
{
Console.WriteLine("Lower");
}
else if (numero > deNumero)
{
Console.WriteLine("Higher");
}
else if (numero == deNumero)
{
Console.WriteLine("Well done!");
Console.ReadKey();
}
else
{
Console.WriteLine("What?");
}
}
Result
I ran your program and found it works, watch out you set the random number range 1 to 100,000, not 1-10,000.. and are you sure you know the value of deNumero?

string array to sort in abc order [closed]

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 8 years ago.
Improve this question
here is my code with the comments. so im having trouble exiting out of the loop. i know it shoud be if(contd = true) or something then it should exit out, but also if they enter Y to keep going, how do i get back into the loop?
another thing is how to sort this by abc order. and then how do i do the reverse from Z-A. Thanks for your help, clueless beginner here.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string lastName;
string [] lastName = new string[]; //array list of last names
int index;
string contd;
for (index=0;index++)
{
Console.Write("Enter a last name: ");
lastName[index] = Convert.ToString(Console.ReadLine());
Console.Write("Keep going? (Y/N): ");
//prompts user to keep inputting or exit out
contd = Convert.ToString(Console.ReadLine());
if (contd = "n"(Console.ReadLine());
{
//exit out of last name input
}
else contd = "y"(Console.ReadLine());
{
//go back into last name input
}
}
Console.WriteLine((index+1) + " last names entered");
//shows how many last names were entered
Console.WriteLine(); //spacing
//display last names
Console.WriteLine("Names in Acsending Order"); Console.WriteLine();
for(index=0; index++)
//shows the last names in order from A-Z (acsending)
{
Console.WriteLine(lastName[index]);
}
Console.WriteLine();
Console.WriteLine("Names in Descending Order"); Console.WriteLine();
for(index=0; index--)
//shows back last names in reverse order Z-A (descending)
{
Console.WriteLine(lastName[index]); Console.WriteLine();
}
Console.ReadLine();
}
}
}
you can use a do while loop:
string d = string.Empty;
do
{
Console.WriteLine("What's your answer?");
d = Console.ReadLine();
}
while (d != "Y");
as for sorting you can use Array.Sort
Array.Sort(array);
You were doing assignments instead of comparisons, and you also ended your if statement lines with a semicolon. The assignment just sets contd to n instead of checking if that is its current value and the semicolon at the end would be overlooking the following braces completely like the following..
if(contd == "n")
;
Which is valid code (not sure why you'd want to do this though). Below is what you seem to be looking for but I still think your for loops are a bit strange
contd = Console.ReadLine(); // Already a string..
if (contd == "n")
{
//exit out of last name input
break;
}
else
{
//go back into last name input
}
To sort these names alphabetically you would be best to look into sorting algorithms such as bubble sort. You could always use linq but I'd imagine this is outside of your classes scope
lastName = lastName.OrderBy(x => x).ToArray();
lastName = lastName.OrderByDescending(x => x).ToArray();

Finding it difficult with the following code [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 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.

C# How Do I parse variable?

//Prompts user for their age
int age;
ApplicationUtilitiesinternal.DisplayDivider("Get Age");
Console.WriteLine("What is your age? ");
while (!int.TryParse(Console.ReadLine(), out age)) //Makes sure the user inputs a number for their age
Console.WriteLine("You did not enter a valid age - try again.");
age = InputUtilities.GetInput("Age");
I know I need to parse the variable, age, but I'm not sure how to do it. I've tried several methods and searched the web for answers. Just when I think I had it...another error would pop up. I know this should be simple.
Edit:
Okay, I'm going to add some context here. Here's what I have to call from:
class InputUtilities
{
internal static string GetInput(string inputType)
{
Console.WriteLine("Enter your " + inputType);
string strInput = Console.ReadLine();
return strInput;
}
}
I hope this makes more sense now.
To answer your actual question: "I know I need to parse the variable, age, but I'm not sure how to do it.", as already stated by others, you ARE doing it.
I've ignored your ApplicationUtilitiesinternal and InputUtilities classes as they don't appear to be relevant to your requirement, along with the fact that InputUtilities.GetInput() returns a string and you are trying to assign it to an int (age).
I suggest this code should make things clearer:
Console.WriteLine("Please enter your age (1-120):");
int nAge;
while(true)
{
string sAge = Console.ReadLine();
if(!int.TryParse(sAge, out nAge))
{
Console.WriteLine("You did not enter a valid age - try again.");
continue;
}
if(nAge <= 0 || nAge > 120)
{
Console.WriteLine("Please enter an age between 1 and 120");
continue;
}
break;
}
// At this point, nAge will be a value between 1 and 120

How do I set up a try catch exception for IndexOutOfRangeException with an array? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 9 years ago.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Improve this question
I have a method that requires user input of an char that relates to an array. I need to use a try catch exception statement to trigger some form of an exception preferably a IndexOutOfRangeException. If the user does not enter the correct char they need to be prompted to input a char again.
private static double dataEntry(string location, int num, int month, Mural[] murals)
{
string entryString;
bool isValid;
int x;
char code;
double tot = 0;
Console.WriteLine("\n\nEntering {0} jobs:", location);
x = 0;
while (x < num)
{
tot += murals[x].Price;
Console.Write("Enter customer name >> ");
murals[x].Name = Console.ReadLine();
Console.WriteLine("Mural options are:");
for (int y = 0; y < Mural.muralCodes.Length; ++y)
Console.WriteLine(" {0} {1}", Mural.muralCodes[y], Mural.muralTypes[y]);
Console.Write(" Enter mural style code >> ");
entryString = Console.ReadLine();
isValid = false;
while (!isValid)
{
try
{
code = char.Parse(entryString);
}
catch (FormatException)
{
Console.WriteLine("Wrong format");
Console.Write(" Enter mural style code >> ");
entryString = Console.ReadLine();
}
catch (IndexOutOfRangeException)
{
Console.WriteLine("Wrong format");
Console.Write(" Enter mural style code >> ");
entryString = Console.ReadLine();
}
finally
{
if (!char.TryParse(entryString, out code))
{
Console.WriteLine("Wrong format");
Console.Write(" Enter mural style code >> ");
entryString = Console.ReadLine();
}
else
{
murals[x].Code = code;
isValid = true;
}
}
}
++x;
}
return tot;
}
You should use function Char.TryParse like this
char output;
if (char.TryParse(whatUserEntered, output))
{
// Char is in output.
}
else
{
//Bad entry by user.
}
If I understand your question correctly, you want to conditionally trigger an exception. Use this code:
if(/* not valid or out of bounds */) {
throw new IndexOutOfRangeException();
}
Refer to the msdn reference below, rewrite your code and post back any more problems.
http://msdn.microsoft.com/en-us/library/ms173165(v=vs.110).aspx
If you're really required to use try/catch, and you want to reprompt the user, try this. I'll explain it all so you understand what's going on ... since it's homework and all.
You're catching multiple exceptions, but there's no need since you're doing the same thing in each one. Just catch and.. do nothing. There's really nothing to do in the catch statement, but at least your program doesn't terminate. In the real world, you'd notify the user, or log the error or something.
While char.Parse fails and throws an exception, your logic will never reach the next two lines (murals[x]... and isValid = true), and your loop will repeat until the user enters a valid character. At that point, isValid is true and exit the while loop.
bool isValid = false;
while (!isValid)
{
Console.WriteLine("Wrong format");
Console.Write(" Enter mural style code >> ");
entryString = Console.ReadLine();
try
{
code = char.Parse(entryString);
murals[x].Code = code;
isValid = true;
}
catch
{
// Just ignore the error
// Bad practice, which is why others are suggesting Char.TryParse
}
}

Categories