Password/Calculator in C# [closed] - c#

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 8 years ago.
Improve this question
I am using Microsoft Visual Studio 2010 and using C# and I am trying to create a program that asks the user for a password and you should have 3 attempts to get it right but I don't know how to add a counter variable or an error message. Can someone help me out?
Also the main part of my program is having the user to choose 2 numbers and having them either subtracted, multiplied, added or divided but my code just automatically does that instead of asking the user. Can anyone help me out with this please?
Here is my code:
static string userName = "";
static string passWord = "";
static float numberOne = 0;
static float numberTwo = 0;
static void Main(string[] args)
{
getpassWord();
validatepassWord();
calculatorIntro();
getData();
calcAddition();
calcSubtraction();
calcDivision();
calcMultiplication();
Console.ReadLine();
}
static void getpassWord()
{
while (passWord == "")
{
Console.Write("Please enter the password > ");
passWord = Console.ReadLine();
}
}
static void validatepassWord()
{
if (passWord == "12345")
{
Console.Write("Please enter a valid password > ");
passWord = Console.ReadLine();
}
}
static void calculatorIntro()
{
Console.Write("Please enter your name > ");
userName = Console.ReadLine();
Console.WriteLine("Hello {0}, Welcome to the Calculator!", userName);
Console.WriteLine("After you have entered the password, you must then enter 2 numbers and decide whether they should be added, multiplied, subtracted or divided");
Console.ReadLine();
}
static void getData()
{
Console.Write("Please enter the first number");
numberOne = float.Parse(Console.ReadLine());
Console.Write("Please enter the second number");
numberTwo = float.Parse(Console.ReadLine());
}
static void calcAddition()
{
Console.Write("{0} + {1} = {2}", numberOne, numberTwo, numberOne + numberTwo);
Console.ReadLine();
}
static void calcSubtraction()
{
Console.Write("{0} - {1} = {2}", numberOne, numberTwo, numberOne - numberTwo);
Console.ReadLine();
}
static void calcDivision()
{
Console.Write("{0} / {1} = {2}", numberOne, numberTwo, numberOne / numberTwo);
Console.ReadLine();
}
static void calcMultiplication()
{
Console.Write("{0} * {1} = {2}", numberOne, numberTwo, numberOne * numberTwo);
Console.ReadLine();
}

For the password validation:
Use a do while loop. The condition to terminate would be if the counter reaches three or if the user gets it right.
example
int counter = 0;
boolean passwordCorrect = false;
do {
Console.Write("Please enter the password > ");
passWord = Console.ReadLine();
//If the password is correct,then it will break the loop
if (passWord == "1234") {
passwordCorrect = true;
}
counter++;
} while (counter < 3 && !passwordCorrect);
You are not even asking the user if they want to subtract, add,etc.For that, ask the user in the main method. Then you will call that method depending on what they inputed.
Example.
int choice;
Console.Write("What operation would you like to perform?\n1. Addition\2. Subtraction");
Console.Write("\n3. Multiplication\n4. Division");
choice = Console.ReadLine();
switch (choice)
{
case 1:
calcAddition();
break;
case 2:
calcSubtraction();
break;
case 3:
calcMultiplication();
break;
case 4:
calcDivision();
break;
default:
Console.Writeline("No operation chosen");
break;
}

Related

Need a loop after a key input

Need to get it to loop after the user presses "r" at this part, need it to do as it says in the Console.WriteLine and redo all the questions
if (numOfCorrect > 7)
Console.Clear();
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine("You got " + numOfCorrect + "correct! Incredible job! Can you do it again though? ");
Console.WriteLine("If you want to retry the quiz press 'r', if you wish to exit the program press 'c'");
if (Console.ReadKey().Key != ConsoleKey.R)
Console.Clear();
using System;
namespace ConsoleApp1
{
class Program
{
static int iNum1;
static int iNum2;
static int numOfCorrect;
static void Main(string[] args)
{
Console.ForegroundColor = ConsoleColor.Cyan;
Console.WriteLine("Ten Question Multiplication Quiz");
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("Instructions");
Console.WriteLine("This program will give you 10 questions on multiplication for you to answer, after answering the ten questions it will display how many you got right!");
Console.WriteLine("If you decide to retry the quiz it will have 10 completely different questions! So be prepared for a challenge.");
Console.ResetColor();
Console.WriteLine("Press Enter to Start");
Console.ReadKey();
Console.Clear();
Random rRandom = new Random();
for (int loop = 0; loop < 10; loop++)
{
int userAnswer;
int answer;
iNum1 = rRandom.Next(11);
iNum2 = rRandom.Next(11);
{
Console.Write("What is " + iNum1 + " times " + iNum2 + "? ");
answer = iNum1 * iNum2;
userAnswer = Convert.ToInt32(Console.ReadLine());
}
if (answer == userAnswer)
{
Console.WriteLine(userAnswer + " is correct ");
numOfCorrect++;
Console.Clear();
}
else
{
Console.WriteLine(userAnswer + " is incorrect ");
Console.Clear();
}
if (userAnswer > 100)
{
loop += (loop - 1);
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("That number is too high, try again");
}
}
{
if (numOfCorrect > 7)
Console.Clear();
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine("You got " + numOfCorrect + "correct! Incredible job! Can you do it again though? ");
Console.WriteLine("If you want to retry the quiz press 'r', if you wish to exit the program press 'c'");
if (Console.ReadKey().Key != ConsoleKey.R)
Console.Clear();
else if (Console.ReadKey().Key != ConsoleKey.C)
System.Environment.Exit(0);
}
}
}
}
You can either capsulate your whole code inside another loop like pawel stated in his comment. Or you could also create a recursive function call like:
static void Main(string[] args)
{
Quiz();
}
void Quiz(){
// Initialize stuff
// Display stuff
for(int loop = 0; loop < 10; loop++)
{
// Question User
// Evaluate Answers
// and so on
// Check user input for retry
if (Console.ReadKey().Key != ConsoleKey.R)
{
Console.Clear();
Quiz(); // <---- Calls the same method again
}
}
}

How to check input is a valid integer [duplicate]

This question already has answers here:
Identify if a string is a number
(26 answers)
Closed 6 years ago.
I try to tell the user that ,whenever he types in a string instead of an integer, he/she should type in a number.But somehow the code within the if statement never shows up.
private static void Number()
{
Console.Write("Type it in a number: ");
int result = int.Parse(Console.ReadLine());
if (float.IsNaN(result))
{
Console.WriteLine("Please type a number!");
}
else
{
Console.Write("Hi");
}
Console.ReadLine();
}
private static void Number()
{
Console.Write("Type it in a number: ");
int result;
bool parsedSuccessfully = int.TryParse(Console.ReadLine(), out result);
if (parsedSuccessfully == false)
{
Console.WriteLine("Please type a number!");
}
else
{
Console.Write("Hi");
}
Console.ReadLine();
}
You can do by int.TryParse for that
private static void Number()
{
Console.Write("Type it in a number: ");
int result;
if (int.TryParse(Console.ReadLine(), out result))
{
// user input a valid integer
// result varaible have the input integer
Console.Write("Hi");
}
else
{
// user input none integer
Console.WriteLine("Please type a number!");
}
Console.ReadLine();
}
Try using TryParse method to validate the entered string , you can also use
int.TryParse
Code :
private static void ValidateInput() {
Console.Write("Type the number: ");
string userInput = Console.ReadLine();
int result;
bool isValidNumber = Int32.TryParse(userInput, out result);
Console.WriteLine(isValidNumber ? "Hi, You have entered a valid number" : "Entered value is not a vald number, so please type a number!");
Console.ReadLine();
}

Cannot implicitly convert type 'string' to 'int'

I'm doing an athlete program and I want to make int salaryCounter = athleteSalary.ToString so when the user enters the salary of the hired professional I can subtract it from the salary of the athlete and print out how much the athlete will have left but when I try to do it the program tells me "Cannot implicitly convert type 'string' to 'int' ". Can someone help me?
{
Console.WriteLine("Please enter the first name of the athlete");
String athleteString = Console.ReadLine();
Console.WriteLine("Please enter the second name of the athlete");
String athleteString2 = Console.ReadLine();
Console.WriteLine("Did you type {0} {1}? Press y for yess n for no.", athleteString.ToString(), athleteString2.ToString());
ConsoleKeyInfo KeyInfo = Console.ReadKey();
if (KeyInfo.KeyChar == 'y')
{
Console.WriteLine("Enter the salary of {0} {1}", athleteString.ToString(), athleteString2.ToString());
String athleteSalary = Console.ReadLine();
Console.WriteLine("{0} Is this right?", athleteSalary.ToString());
ConsoleKeyInfo rightathleteSalary = Console.ReadKey();
int salaryCounter = athleteSalary.ToString();
if (rightathleteSalary.KeyChar == 'y')
{
Console.WriteLine("Ok. Lets contiune.");
athleteSalary = Convert.ToString(salaryCounter);
Console.WriteLine(salaryCounter);
int counter = 0;
Console.WriteLine("{0} {1} {2}", athleteString.ToString(), athleteString2.ToString(), salaryCounter.ToString());
Console.WriteLine("Enter the hired help. The max number of people is five. Press any key to start.");
while (counter < 5)
{
Console.ReadKey();
Console.WriteLine("Please enter the first name of the hired help");
String hiredhelpString = Console.ReadLine();
Console.WriteLine("Please enter the Last name of the hired help");
String hiredhelpString2 = Console.ReadLine();
Console.WriteLine("Did you type {0} {1}? Press y for yess n for no.", hiredhelpString.ToString(), hiredhelpString2.ToString());
ConsoleKeyInfo KeyInfo5 = Console.ReadKey();
if (KeyInfo5.KeyChar == 'y')
{
Console.WriteLine("Enter the salary of {0} {1}", hiredhelpString.ToString(), hiredhelpString2.ToString());
String hiredhelpSalary = Console.ReadLine();
Console.WriteLine("{0} Is this right?", hiredhelpSalary.ToString());
ConsoleKeyInfo rightSalary = Console.ReadKey();
if (rightSalary.KeyChar == 'y')
{
Console.WriteLine("Ok. Lets contiune.");
}
Console.WriteLine("Record this proffesional? Press y for yess n for no.");
ConsoleKeyInfo RecordKey = Console.ReadKey();
if (RecordKey.KeyChar == 'y')
{
counter = counter + 1;
Console.WriteLine("Number of hired help is {0} They will be paid {1}", counter, hiredhelpSalary);
Console.WriteLine("Press any key to contiune.");
}
else
{
if (RecordKey.KeyChar == 'n')
{
counter = counter - 1;
Console.WriteLine(" Ok. Lets try again. Press any key to contiune.");
Console.ReadKey();
Console.WriteLine("Please enter the first name of the hired help");
String hiredhelpString3 = Console.ReadLine();
Console.WriteLine(" Please enter the Last name of the hired help");
String hiredhelpString4 = Console.ReadLine();
Console.WriteLine("Did you type {0} {1}? Press y for yess n for no.", hiredhelpString.ToString(), hiredhelpString2.ToString());
ConsoleKeyInfo KeyInfo6 = Console.ReadKey();
if (KeyInfo6.KeyChar == 'y')
{
Console.WriteLine("Record this proffesional? Press y for yess n for no.");
ConsoleKeyInfo RecordKey1 = Console.ReadKey();
if (RecordKey.KeyChar == 'y')
{
counter = counter + 1;
Console.WriteLine("Number of Hired help is {0} press any key to contiune", counter);
Console.WriteLine("Press any key to contiune.");
}
}
}
}
/*******************************************************************************************************/
/************************************************************************************************************************************************************************************************************************************************/
}
else
{
if (KeyInfo5.KeyChar == 'n')
{
Console.WriteLine(" Ok. Lets try again. Press any key to contiune.");
Console.ReadKey();
}
}
}
/*************************************************************************************************************************************************************************************************************************************/
Console.WriteLine("");
Console.WriteLine("Athlete's name: {0} {1} Number of Hired help is {2}", athleteString.ToString(), athleteString2.ToString(), counter);
Console.ReadKey();
}
It looks like you're getting confused about variable types. Briefly;
string - stores information character by character. The compiler can't read numbers stored in strings.
int - stores whole numeric values which can be used in calculations.
Your immediate compile problem comes from this line;
int salaryCounter = athleteSalary.ToString();
You're telling the compiler to take altheteSalary which is a string, call the ToString() method which gets the string representation (this is unnecessary when the source is a string) and store the result in an integer.
You need to parse the string to read out the numeric value like this;
int salaryCounter = int.Parse(athleteSalary)
Though, whenever you receive input directly from a user you should code defensively, so instead of int.Parse, use TryParse. That way if your user enters 'Bob' for their salary, you can display an appropriate error;
int salaryCounter;
while(!int.TryParse(athleteSalary, out salaryCounter)
{
Console.Writeline("The salary should be a number, try again");
athleteSalary = Console.ReadLine();
}
Also, you can remove most of the calls to .ToString(), especially where the variable is already a string.
The main issue is that you need to convert your user input to a type other than a string.
There are many ways to do this, but since you are writing a console application that relies heavily on user-entered data, and since some of this data has to be converted to types other than strings, you might consider writing some helper methods that take care of some of the converting and retrying for you.
I've used the following class in several applications with success. Basically, it's just a bunch of methods that accept a string 'prompt' and return a strongly typed result from the user. If the user enters invalid data, then they have to try again until the enter something valid:
class UserInput
{
public static bool GetBool(string prompt)
{
bool result;
List<string> validTrueResponses =
new List<string> {"yes", "y", "true", "t", "affirmative",
"ok", "okay", "yea", "yeah", "yep"};
List<string> validFalseResponses =
new List<string> {"no", "n", "false", "f", "negative",
"never", "not", "nay", "nix"};
while (true)
{
if (prompt != null) Console.Write(prompt);
var input = Console.ReadLine();
if (validTrueResponses.Any(r =>
r.Equals(input, StringComparison.OrdinalIgnoreCase))) return true;
if (validFalseResponses.Any(r =>
r.Equals(input, StringComparison.OrdinalIgnoreCase))) return false;
if (bool.TryParse(input, out result)) break;
Console.WriteLine("Sorry, I don't understand that response. " +
"Please try again.");
}
return result;
}
public static string GetString(string prompt)
{
if (prompt != null) Console.Write(prompt);
return Console.ReadLine();
}
public static int GetInt(string prompt)
{
int input;
while (true)
{
if (prompt != null) Console.Write(prompt);
if (int.TryParse(Console.ReadLine(), out input)) break;
Console.WriteLine("Sorry, that is not valid. Please try again.");
}
return input;
}
public static decimal GetDecimal(string prompt)
{
decimal input;
while (true)
{
if (prompt != null) Console.Write(prompt);
if (decimal.TryParse(Console.ReadLine(), out input)) break;
Console.WriteLine("Sorry, that is not valid. Please try again.");
}
return input;
}
}
Then, I would create a simple class to represent a Person, which has simply a first name, last name, and salary (and override the ToString method to display first and last name):
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
public decimal Salary { get; set; }
public override string ToString()
{
return string.Format("{0} {1}", FirstName, LastName);
}
}
Now we can reduce some duplicated code by creating methods to get a Person name and salary. This will prompt the user for the information, and then give them a chance to correct it before commiting the data:
private static void GetPersonName(Person person, string typeOfPerson)
{
if (person == null) throw new ArgumentNullException("person");
if (string.IsNullOrWhiteSpace(typeOfPerson)) typeOfPerson = "person";
bool inputIsGood = false;
while (!inputIsGood)
{
person.FirstName = UserInput.GetString(
string.Format("Please enter the first name of the {0}: ", typeOfPerson));
person.LastName = UserInput.GetString(
string.Format("Please enter the last name of the {0}: ", typeOfPerson));
Console.WriteLine("You entered: {0}", person);
inputIsGood = UserInput.GetBool("Is that correct (y/n): ");
}
}
private static void GetPersonSalary(Person person)
{
bool inputIsGood = false;
while (!inputIsGood)
{
person.Salary = UserInput.GetDecimal(
string.Format("Enter the salary of {0}: $", person));
Console.WriteLine("You entered: {0:C}", person.Salary);
inputIsGood = UserInput.GetBool("Is that correct (y/n): ");
}
}
That may seem like a lot of code, but here's how you can use it in your application:
private static void Main()
{
var athlete = new Person();
GetPersonName(athlete, "athlete");
GetPersonSalary(athlete);
Console.WriteLine("Enter the hired help. The max number of people is five. " +
"Press any key to start.");
Console.ReadKey();
List<Person> hiredHelpers = new List<Person>();
while (hiredHelpers.Count <= 5)
{
bool addAnotherHelper =
UserInput.GetBool(
string.Format("There are currently {0} helpers. " +
"Do you want to add another (y/n): ",
hiredHelpers.Count));
if (!addAnotherHelper) break;
Person helper = new Person();
GetPersonName(helper, "helper");
GetPersonSalary(helper);
bool recordHelper = UserInput.GetBool("Do you want to record this " +
"professional (y/n): ");
if (recordHelper)
{
hiredHelpers.Add(helper);
}
}
Console.WriteLine();
Console.WriteLine("Athlete's name: {0}, salary: {1:C}.", athlete, athlete.Salary);
Console.WriteLine("Number of Hired help is: {0}", hiredHelpers.Count);
Console.WriteLine("Hired help details:");
hiredHelpers.ForEach(h =>
Console.WriteLine(" - Name: {0}, Salary: {1:C}", h, h.Salary));
Console.ReadKey();
}

C# Console Program Loop Issue

I have tried to create a C# program that gives the user 3 options:
Create name (gets the user to enter their first name and surname and display it as J.Blogg)
Factorial of a number (outputs as for example 5x4x3x2x1 =120 which is the factorial of 5
Quit
I have the program work fine but when I try picking option 1 (create name) and then option 2 it goes to option 1 instead and then it doesn't lets me Quit (option 3).
I'm new to programming so it could be simple but I can't see where i'm going wrong,
Any help would be very greatful.
I want to keep the same layout, I think my problem could be the loops but any help and improvement would be great.
static void Main(string[] args)
{
//The value returned from the topmenu method is stored in a variable called useroption
int useroption;
useroption = topmenu();
// excute while loop untill option is not 1-3
do
{
if (useroption == 1)
{
Console.Clear();
Createname();
//break;
}
if (useroption == 2)
{
Console.Clear();
factorial();
// break;
}
if (useroption == 3)
{
Console.Clear();
Console.WriteLine("Thank you for using my program, Good bye !!!");
// break;
}
//topmenu();
}
while (useroption != 3);
Console.ReadKey();
}
//This method present the user with an menu which the user has a choice of 3 options
static int topmenu()
{
int option;
string option_str;
Console.Clear();
Console.WriteLine("********************************************************************************");
Console.WriteLine("********************************************************************************");
Console.WriteLine("********* OPTION 1 : Enter your name *********");
Console.WriteLine("********* OPTION 2 : Enter the number you want to factorise *********");
Console.WriteLine("********* OPTION 3 : Quit *********");
Console.WriteLine("********************************************************************************");
Console.WriteLine("********************************************************************************");
option_str = Console.ReadLine();
option = Convert.ToInt32(option_str);
Console.Clear();
if (option < 0 || option > 3)
{
Console.WriteLine("You have enter an invald option,");
Console.WriteLine("Please chose a option between 1-3 (Please press any key to return to main menu)");
Console.ReadLine();
Console.Clear();
topmenu();
}
else
{
Console.WriteLine("You have chosen option: " + option + " (Please press any key continue)");
}
Console.ReadKey();
return option;
}
//this method asks user to enter their name (1st name then surname) and presents it back to the user as their intial(1st name) and surname
static void Createname()
{
string firstname, surname, firstname_str, surname_str, userfullname;
Console.Clear();
Console.WriteLine("Please enter your first name ");
firstname_str = Console.ReadLine();
firstname = Convert.ToString(firstname_str);
Console.Clear();
Console.WriteLine("Please enter your surname name ");
surname_str = Console.ReadLine();
surname = Convert.ToString(surname_str);
Console.Clear();
userfullname = firstname + surname;
Console.WriteLine("You have entered your name as " + firstname[0] + "." + surname);
Console.WriteLine("(Please press any key to return to main menu)");
Console.ReadKey();
topmenu();
}
//this method asks the user to enter a number and returns the factorial of that number
static double factorial()
{
string number_str;
double factorial = 1;
Console.WriteLine("Please enter number");
number_str = Console.ReadLine();
int num = Convert.ToInt32(number_str);
// If statement is used so when the user inputs 0, INVALID is outputed
if (num <= 0)
{
Console.WriteLine("You have enter an invald option");
Console.WriteLine("Please enter number");
number_str = Console.ReadLine();
Console.Clear();
num = Convert.ToInt32(number_str);
//Console.Clear();
//topmenu();
//number_str = Console.ReadLine();
}
if (num >= 0)
{
while (num != 0)
{
for (int i = num; i >= 1; i--)
{
factorial = factorial * i;
Console.Write(i + " * ");
}
Console.WriteLine("= "+factorial+ " which is factorial of " + number_str.ToString() );
Console.WriteLine("(please any key to return to main menu)");
Console.ReadKey();
Console.Clear();
topmenu();
}
}
return factorial;
}
}
}
Just put these line inside do...while
int useroption;
useroption = topmenu();
rearrange as following...
int useroption;
// excute while loop untill option is not 1-3
do
{
useroption = topmenu();
and your program will work fine
The full code is here : http://pastebin.com/fCh0ttUY
First of al, set useroption to 0 after executing some code. Otherwise it will keep executing it.
Second, ReadKey() right before your while statement. Otherwise you won't be able to read the input.
The issue is that although you display topmenu again you never re-assign the value of useroption.
As gypsyCoder said, moving the display of your menu inside the do{}while() block will fix your issue because it will cause the useroption to be re-assigned each time round the loop.

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