Small coding project won't catch FormatException - c#

So I recently started my first coding course for C#. I am currently trying to write a short program that prints out Yay! as many times as I indicate. Now to prevent any format exceptions, I've tried to add a try and catch to it. But, for some reason this isn't working and I can't seem to figure out why. The code is below:
Console.Write("Enter the number of times to print \"Yay!\": ");
string entry = Console.ReadLine();
var number = int.Parse (entry);
bool print = true;
while(print)
{
try
{
if(number <= 0)
{
print = false;
}
else
{
Console.WriteLine("Yay!");
number -= 1;
}
}
catch(FormatException)
{
Console.WriteLine("You must enter a whole number.");
}
}
Now to my knowledge, I have everything I need to make this work. Can anyone see where I went wrong with this?
Thanks a lot for reading!

It's
var number = int.Parse (entry);
that should throw the exception, and since it's beyond try {} scope, the
exception has not been caught. Move the fragment into the scope:
Console.Write("Enter the number of times to print \"Yay!\": ");
string entry = Console.ReadLine();
bool print = true;
try {
// int.Parse is within the try {} scope now
var number = int.Parse (entry);
while(print) {
...
}
}
catch(FormatException) {
Console.WriteLine("You must enter a whole number.");
}
Or convert int.Parse into int.TryParse and drop try {...} catch {...} at all (a better solution)
Console.Write("Enter the number of times to print \"Yay!\": ");
int number;
if (!int.TryParse(Console.ReadLine(), out number)) {
Console.WriteLine("You must enter a whole number.");
return;
}
bool print = true;
// There's no need in try {} catch {} now
while(print) {
...
}

You need to place your int.Parse inside your try-catch block.
Here's a revised version of your code.
static void Main(string[] args)
{
bool print = true;
while (print)
{
Console.Write("Enter the number of times to print \"Yay!\": ");
string entry = Console.ReadLine();
try
{
var number = int.Parse(entry);
for (int i = 0; i < number; i++)
{
Console.WriteLine("Yay!");
}
}
catch (FormatException)
{
Console.WriteLine("You must enter a whole number.");
}
}
}

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 ? :- ");

Number guessing game using TryParse

I´m having problems with getting my code to work while using TryParse to catch if the user where to input a string instead of a int. If I use it as it looks now I only get the base value of 0 if something other than an int is input. I want it to show an error message to the user.
Have tried messing around with a number of different ways of using TryParse but none of them has really been helpfull.
static void Main(string[] args)
{
Random r = new Random();
int speltal = r.Next(1,21);
bool play = false;
int myNum;
while (!play)
{
Console.Write("\n\tGuess a number between 1 and 20: ");
Int32.TryParse(Console.ReadLine(), out myNum);
if (myNum < guessNum)
{
Console.WriteLine("\tThe number you have guessed is to low");
Console.ReadLine();
}
if (myNum > guessNum)
{
Console.WriteLine("\tThe number you have guessed is to high");
Console.ReadLine();
}
if (myNum == guessNum)
{
Console.WriteLine("\tCongratulations you guessed the right number!");
Console.ReadLine();
}
I want it show an error message to the user if they put in anything other than a int. It also have to include TryParse according to my teatcher
You're not capturing the bool output of TryParse so you have no idea if a non-numeric value was entered. Try something like this:
bool isValid;
do
{
Console.Write("\n\tGuess a number between 1 and 20: ");
isValid = Int32.TryParse(Console.ReadLine(), out myNum);
if(!isValid)
{
Console.WriteLine("\n\tInvalid input detected. Please try again.");
}
} while(!isValid)
The TryParse method can only put integers in the passed variable (as it is of type int), so if the value passed to it can't be parsed into an integer, the default value of int (0) will be assigned to the variable.
The way TryParse tell you if it successfully parsed the number or not, is by returning a boolean indicator.
You can try this:
while (true)
{
bool valid = int.TryParse(Console.ReadLine(), out myNum);
if(valid)
break;
Console.WriteLine("Input invalid. Please try again");
}
TryParse returns a Boolean which indicates if the input string was successfully parsed or not. Both of the answers above are correct on how to handle a invalid input but, here is a cleaner version which will also uphold the rule, between 1 and 20:
while (true)
{
Console.Write("\n\tGuess a number between 1 and 20: ");
//Checks to see if the input was successfully parsed to a integer also, performs a Trim on the input as to remove any accidental white spaces that a user might have typed in, e.g. "1000 "
if (int.TryParse(Console.ReadLine().Trim(), out myNum))
{
//Checks to see if the parsed number is in the specified range
if ((myNum > 0) && (myNum < 21))
{
break;
}
Console.WriteLine("\tThe input number was out of the specified range.");
}
else
{
Console.WriteLine("\tFailed to parse the input text.");
}
//Optional, makes the thread sleep so the user has the time to read the error message.
Thread.Sleep(1500);
//Optional, clears the console as to not create duplicates of the error message and the value of Console.Write
Console.Clear();
}
// Continue here, if (myNum < guessNum) . . .
You should use the bool returned by TryParse. Something that looks like this:
Updated answer:
static void Main(string[] args)
{
Random random = new Random();
int guessNum = random.Next(1, 21);
while(true)
{
Console.WriteLine("Guess the number between 1 and 21.");
if (Int32.TryParse(Console.ReadLine(), out int input))
{
if (input == guessNum)
{
Console.WriteLine($"You guessed it right. The number is {input}");
if(ShouldContinue())
{
guessNum = random.Next();
continue;
}
else
{
break;
}
}
if (input < guessNum)
Console.WriteLine("The number you guessed is smaller.");
else
Console.WriteLine("The number you guessed is bigger");
}
else
{
Console.WriteLine("Please enter a number between 1 and 21 as your guess");
}
}
}
static bool ShouldContinue()
{
while (true)
{
Console.WriteLine($"Do you want to continue playing? (y/n)");
string continueInput = Console.ReadLine().Trim().ToLower();
if (continueInput == "y")
return true;
else if (continueInput == "n")
return false;
else
Console.WriteLine("Invalid input!. Please choose 'y' or 'n'.");
}
}
Old answer:
while (true)
{
if (Int32.TryParse(inputInt, out int myNum))
{
// your logic goes here, too low/high or correct answer.
}
}

Try Catch C# How Do I do it?

im working on a assignment where I now have to implement the Try & Catch-method too catch inputs other than numbers in my program. I understand the process and explanations in my study-book and have also done some minor examples while trying it out. But when I want to implement this into my assignment I am getting stuck. Can someone please explain to me in a manor as to not spoil anything but try and help me along the way?
Here is my code:
using System;
namespace BastunKP
{
class Program
{
public static double FahrToCels(double fahr)
{
return (fahr - 32) * 5 / 9;
}
public static void Main(string[] args)
{
Console.WriteLine("Skriv in Fahrenheit: ");
double fahr = Convert.ToDouble(Console.ReadLine());
double tempCels = FahrToCels(fahr);
do
{
try
{
//Dont know what to write here.
}
catch
{
Console.WriteLine("Du kan bara skriva in siffor, testa igen.");
}
if (tempCels < 73)
{
Console.WriteLine("Temperaturen är för kallt, skruva upp lite!");
}
else if (tempCels > 77)
{
Console.WriteLine("Temperaturen är för varmt, skruva ner lite!");
}
else
{
Console.WriteLine("Temperaturen är nu bra, hoppa in!");
Console.ReadKey();
}
fahr = Convert.ToDouble(Console.ReadLine());
tempCels = FahrToCels(fahr);
}
while (tempCels < 73 || tempCels > 77);
return;
}
}
}
First of all, lets write code without any exception handling. Get the basics right first. We need a method that:
Asks the user for a temperature in Fahrenheit.
If the input is not a valid double, go to 1.
Convert the value to Celsius.
If not, go to 1.
If the temperature in Celsius does not belong to (73, 77) go to 1.
public static double GetTemperatureFromUser()
{
while (true)
{
Console.Write("Enter temperature in Fahrenheit: ");
var t = FahrToCels(Convert.ToDouble(Console.ReadLine()));
if (t < 73)
{
Console.Write("Temperature is too low. Try again.");
}
else if (t > 77)
{
Console.Write("Temperature is too high. Try again.");
}
else
{
return t;
}
}
}
Ok, that looks good. Now let's add some exception handling. First question: what can go wrong here and throw an exception?
var t = FahrToCels(Convert.ToDouble(Console.ReadLine()));
seems like a likely suspect. Is there anything else that can throw? Hmmm, no.
Ok, second question: what code shouldn't be executing if ToDouble() throws? Well, anything that depends on the result of ToDouble() obviously. So all that code also goes in the try block.
Ok, third question: what code should run if ToDouble() throws? In our case we should inform the user that the input was not a valid double. Ok, that code needs to go in catch block.
Think of try-catch as a fancy if that controls the execution path of your code: if the code throws, go to catch if not, keep executing normally inside the try block.
Fourth question: what code should run after everything else inside the try or catch blocks no matter what happens? In your case nothing, but if there were, it would go in the finally block.
Note that catch and finally blocks are not mandatory. The only rule is that at least one of them must be present immediately following a try block; try-catch, try-finally and try-catch-finally are all valid.
Fifth and last: what exceptions do you want to handle? You should always handle only the exceptions that you know how to handle and ignore all others. What exceptions can ToDouble throw? If you read the documentation you'll see it can throw FormatException and OverflowException. You can handle both because they amount to the same thing: and invalid user input.
Ok, lets rewrite our method:
Does the while loop depend on whatever happens in ToDouble? No, the method should be running in a loop no matter what happens inside; the only way to exit the loop is when the user inputs a valid number and the method returns. Ok then, the while block goes outside any exception handling and so does the user prompt:
public static double GetTemperatureFromUser()
{
while (true)
{
Console.Write("Enter temperature in Fahrenheit: ");
//...
}
}
And now the next instruction is our primary suspect, so it obviously must go inside the try block. Everything else we've written in our method depends on the value of t so we put all that also inside the try block:
public static double GetTemperatureFromUser()
{
while (true)
{
Console.Write("Enter temperature in Fahrenheit: ");
try
{
var t = FahrToCels(Convert.ToDouble(Console.ReadLine()));
if (t < 73)
{
Console.Write("Temperature is too low. Try again.");
}
else if (t > 77)
{
Console.Write("Temperature is too high. Try again.");
}
else
{
return t;
}
}
}
}
Ok, now we're only missing the catch block. We'll add one for each exception we know how to handle:
public static double GetTemperatureFromUser()
{
while (true)
{
Console.Write("Enter temperature in Fahrenheit: ");
try
{
var t = FahrToCels(Convert.ToDouble(Console.ReadLine()));
if (t < 73)
{
Console.Write("Temperature is too low. Try again.");
}
else if (t > 77)
{
Console.Write("Temperature is too high. Try again.");
}
else
{
return t;
}
}
catch (FormatException)
{
Console.Write("Invalid number format. Try again.");
}
catch (OverflowException)
{
Console.Write("Number is too large or too small. Try again.");
}
}
}
And there you go, we're done.
There is no required try/catch to check valid input. You could use double.TryParse;
Console.WriteLine("Skriv in Fahrenheit: ");
double fahr;
double tempCels;
bool isInputCorrect = false;
while (!isInputCorrect)
{
var input = Console.ReadLine();
if (!double.TryParse(input, out fahr))
{
Console.WriteLine("Du kan bara skriva in siffor, testa igen.");
continue;
}
tempCels = FahrToCels(fahr);
if (tempCels < 73)
{
Console.WriteLine("Temperaturen är för kallt, skruva upp lite!");
continue;
}
else if (tempCels > 77)
{
Console.WriteLine("Temperaturen är för varmt, skruva ner lite!");
continue;
}
isInputCorrect = true;
}
Console.WriteLine("Temperaturen är nu bra, hoppa in! tempCels : " + tempCels);
Console.ReadKey();
If you insist to use try/catch, you could try like this;
Just replace double.TryParse part.
var input = Console.ReadLine();
try
{
fahr = Convert.ToDouble(input);
}
catch (Exception e)
{
Console.WriteLine("Du kan bara skriva in siffor, testa igen.");
continue;
}

How do I remove 'goto' here

I've read that using "goto" in C# is not recommended
However, my code uses goto and so far, errors appeared when trying to avoid "goto"
anum1r:
Console.Write ("What is the first number? ");
try {
num1 = Convert.ToDouble (Console.ReadLine ());
} catch (System.FormatException) {
Console.Beep ();
Console.WriteLine ("");
Console.WriteLine ("You have entered an invalid number!");
Console.WriteLine ("");
goto anum1r;
}
anum2r:
Console.Write ("What is the second number? ");
try {
num2 = Convert.ToDouble (Console.ReadLine ());
} catch (System.FormatException) {
Console.Beep ();
Console.WriteLine ("");
Console.WriteLine ("You have entered an invalid number!");
Console.WriteLine ("");
goto anum2r;
}
answer = num1 + num2;
How do I transform this code without using GOTO. ty
Use a while loop:
double num1;
while (true) {
Console.Write ("What is the first number? ");
try {
num1 = Convert.ToDouble (Console.ReadLine ());
break;
} catch (System.FormatException) {
Console.Beep ();
Console.WriteLine ("");
Console.WriteLine ("You have entered an invalid number!");
Console.WriteLine ("");
}
}
As you need this code twice, it is also a good idea to refactor it in a separate method like #James' answer. (Though it needs an extra parameter to modify the user prompt.)
You could use a while loop
private double? GetNumber()
{
double? result = null;
try {
result = Convert.ToDouble (Console.ReadLine ());
} catch (System.FormatException) {
Console.Beep ();
Console.WriteLine ("");
Console.WriteLine ("You have entered an invalid number!");
Console.WriteLine ("");
}
return result;
}
...
// prompt for first number
double? num1 = null;
while (!num1.HasValue)
{
Console.Write ("What is the first number? ");
num1 = GetNumber();
}
// prompt for second number
double? num2 = null;
while (!num2.HasValue)
{
Console.Write ("What is the second number? ");
num2 = GetNumber();
}
// calculate result
answer = num1.Value + num2.Value;
There are two good ways to improve your code:
Extract into a separate method the logic for repeatedly asking the user for a number until they enter a valid one. (Use a loop construct to handle looping rather than a goto.)
Use double.TryParse() to avoid having to catch a format exception.
If you put both of those together, you get code that looks something like this:
using System;
namespace Demo
{
public static class Program
{
private static void Main()
{
double first = askForNumber("What is the first number? ");
Console.WriteLine();
double second = askForNumber("What is the second number? ");
Console.WriteLine("\nYou entered {0} and {1}", first, second);
}
private static double askForNumber(string prompt)
{
while (true)
{
Console.Write(prompt);
double result;
if (double.TryParse(Console.ReadLine(), out result))
return result;
Console.Beep();
Console.WriteLine("\nYou have entered an invalid number!\n");
}
}
}
}
You can use a for-loop and a collection like a double[], also use double.TryParse:
int numbers = 10;
double[] allNumbers = new double[numbers];
for (int i = 0; i < numbers; i++)
{
Console.Write("What is the {0}. number? ", i + 1);
double num;
if (double.TryParse(Console.ReadLine().Trim(), out num))
{
allNumbers[i] = num;
}
else
{
i--; // ask the user until we have the numbers
Console.Beep();
Console.WriteLine("");
Console.WriteLine("You have entered an invalid number!");
Console.WriteLine("");
}
}
double answer = allNumbers.Sum(); // LINQ so add using System.Linq;
Another way is to extract a method for this purpose:
private static double? ReadNumberFromConsole()
{
double num;
if (double.TryParse(Console.ReadLine().Trim(), out num))
return num;
else
return null;
}
That makes the code more readable:
for (int i = 0; i < numbers; i++)
{
Console.Write("What is the {0}. number? ", i + 1);
double? num = ReadNumberFromConsole();
if (num.HasValue)
{
allNumbers[i] = num.Value;
}
else
{
i--; // ask the user until we have the numbers
Console.Beep();
Console.WriteLine("");
Console.WriteLine("You have entered an invalid number!");
Console.WriteLine("");
}
}
I would also highly recommend avoid using Convert.ToDouble on user input.
Using exceptions as an input validating system is wrong on every level.
Use something like this instead:
double GetNumberFromUser() {
double Num = double.NaN;
while(!double.tryParse(Console.ReadLine(), out Num) && !double.IsNaN(Num))
{
Console.Beep();
Console.WriteLine("");
Console.WriteLine("You have entered an invalid number!");
Console.WriteLine("");
}
return Num;
}
why test for IsNaN also? read this.
You MAY simply use a loop:
double PromptForNumber(string message) {
while (true) {
Console.Write(message + " ");
try {
return Convert.ToDouble(Console.ReadLine());
} catch (FormatException) {
Console.Beep();
Console.WriteLine();
Console.WriteLine("You have entered an invalid number!");
Console.WriteLine();
}
}
}
Used as:
double num1 = PromptForNumber("What is the first number?");
double num2 = PromptForNumber("What is the second number?");
BUT here you're also using exceptions where they're not necessary. Invalid user input is not exceptional and there are better ways to handle that:
double PromptForNumber(string message) {
while (true) {
Console.Write(message + " ");
double number;
if (Double.TryParse(Console.ReadLine(), out number))
return number;
Console.Beep();
Console.WriteLine("\nYou have entered an invalid number!\n");
}
}
Note that this way you'll also handle OverflowException that you left out in your original code.
Do you need 100 inputs? One line of code:
var inputs = Enumerable.Range(1, 100)
.Select(x => PromptForNumber(String.Format("Enter number #{0}:", x)));
private Double InputNum1
{
Console.Write ("What is the first number? ");
try
{
num1 = Convert.ToDouble (Console.ReadLine ());
return num1;
}
catch (System.FormatException)
{
Console.Beep ();
Console.WriteLine ("");
Console.WriteLine ("You have entered an invalid number!");
Console.WriteLine ("");
InputNum1();
}
}
you can use a while to query for numbers until they are valid:
double? num1 = null;
while (num1==null){
Console.Write ("What is the first number? ");
try {
num1 = Convert.ToDouble (Console.ReadLine ());
} catch (System.FormatException) {
Console.Beep ();
Console.WriteLine ("");
Console.WriteLine ("You have entered an invalid number!");
Console.WriteLine ("");
}
}

Escaping a function to get back to Main()

I'm making a program that has little programs inside of it, and I've come to a dilemma. On my first mini-program which rearranges digits to find the greatest possible number from those digits, it asks if the user wants to quit. If they respond "Yes" then the function returns 0 which is evaluated in the main(string[] args) method. My problem is that whenever the user says "No", the mini-program still doesn't continue. Here's my source:
namespace ACSL_Competition
{
class Program
{
static int DigitRearranger()
{
string[] mainString = {};
Console.WriteLine("---------Welcome to the Digit Re-arranger!---------");
Console.WriteLine("I take a positive number up to 10000, and find the highest number that can be made out of its digits.");
Console.WriteLine("Instructions: Enter a number up to 10000, and see the results!");
drLabel:
Console.Write("Your Number: ");
string input = Console.ReadLine();
int inputNumber = 0;
try { inputNumber = int.Parse(input); }
catch (Exception ex) { Console.WriteLine("Error: {0}", ex.Message); goto drLabel; }
/*Placeholder code for the moment*/Console.WriteLine(inputNumber.ToString());
evaluate:
Console.Write("Do you want to exit? Yes/No: ");
if (Console.ReadLine().Equals("Yes"))
return 1;
else if (Console.ReadLine().Equals("No"))
{
goto drLabel;
}
else
{
return 1;
}
}
static void Main(string[] args)
{
Console.WriteLine("Welcome to the ACSL Competition Program. Choose a program to begin:");
Console.Write("\n\t");
Console.WriteLine("1\tDigit Re-arranger");
label:
Console.Write("\nProgram: ");
string input = Console.ReadLine();
int number = 0;
try { number = int.Parse(input); }
catch (Exception ex) { Console.WriteLine("Error: {0}", ex.Message); goto label; }
if (number == 1)
{
Console.WriteLine("\n");
if (DigitRearranger() == 1)
{
goto label;
}
else if (DigitRearranger() != 1)
{
DigitRearranger();
}
}
else if (!number.Equals(1))
{
Console.WriteLine("Not a valid program.");
goto label;
}
//----------------
Console.ReadLine();
}
}
}
The underlying problem is that you're calling readline twice. The first time it gets the entered value, i.e. Yes, the second time you call it there is no data to read so it returns "". If you need to reuse the same input store it in a variable, i.e.
string inputVal = Console.ReadLine();
I hate goto statements, maybe you could restructure your code in to a while loop, something like:
bool exit = false;
while(!exit)
{
Console.Write("Your Number: ");
//Your main code
Console.Write("Do you want to exit? Yes/No: ");
if(Console.ReadLine() != "No")
exit = true;
}
In fact, you could get rid of the exit variable, just do while(true) and return if the user enters anything other than no.
I have a few suggestions:
Write your code to be more modular to improve readability. The Main() method should only drive the outer UI loop, each module provides its own UI.
Never use goto statements.
Don't use Console.Readline() inside an if condition (when not "Yes", it was called twice).
Here is my refactored version of your code:
class Program {
static void DigitRearranger()
{
string response = "";
int num;
do
{
Console.Clear();
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine("---------Welcome to the Digit Re-arranger!---------");
Console.WriteLine("I take a positive number up to 10000, and find the highest number that can be made out of its digits.");
Console.WriteLine("Instructions: Enter a number up to 10000, and see the results!");
Console.ResetColor();
Console.Write("Your Number: ");
if (!int.TryParse(Console.ReadLine(), out num))
{
Console.WriteLine("Not a number. Press any key to continue");
Console.ReadKey();
continue;
}
//todo: reaarrange the number & print results
/*Placeholder code for the moment*/
Console.WriteLine(num);
Console.Write("Do you want to exit? Yes/No: ");
response = Console.ReadLine();
} while (response.ToLower() != "yes");
}
//UI driver only in Main method:
static void Main(){
string response = "";
do
{
Console.Clear();
Console.WriteLine("Welcome to the ACSL Competition Program. Choose a program to begin:");
Console.WriteLine("\n\t1\tDigit Re-arranger");
Console.WriteLine("\tq\tQuit");
Console.Write("\nProgram: ");
response = Console.ReadLine();
switch(response)
{
case "1":
DigitRearranger();
break;
case "q":
break;
default:
Console.WriteLine("Not a valid program. Press any key to continue");
Console.ReadKey();
break;
}
} while (response.ToLower() != "q");
Console.ReadLine();
}}

Categories

Resources