using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
enter code here`namespace fuel_consumption {
class Program {
// Program Reset & exit method at the end of program
static bool DoItAgain()
{
bool startAgain = true;
string reply = "";
Console.Write("Start Over? (Y or N): ");
reply = Console.ReadLine();
reply = reply.ToUpper();
if (reply != "Y")
{
startAgain = false;
}
return startAgain;
}//End DoItAgain method
//Startup Screen method
static void WelcomeMessage() {
Console.WriteLine("\n\n\tWelcome to the Fuel Consumption Calculator\n\n\t");
}// End startup Screen method
//Begin user input method for Number of Litres
static int InputLitres() {
string userInput = "";
int selection = 0;
int minLitres = 20;
bool inValid = true;
//User Input Message
while (inValid) {
Console.Write("\nEnter the amount of litres consumed: ");
the program keeps asking this question over and over, about 5 times infact.
userInput = Console.ReadLine();
if (int.TryParse(userInput, out selection))
if (selection < minLitres) {
// Deliver Error Message to User
Console.Write("\nPlease Enter an amount 20 litres or above\n\n Please Try Again:\n");
}
else {
inValid = false;
}
}
//return the value entered by the user
return selection;
}//end InputLitres
//Begin InputKM method
static int InputKM() {
//set user input varibles
string userInput = "";
int selection = 0;
int inputLitres = InputLitres();
int minKms = 8 * inputLitres;
bool inValid = true;
while (inValid) {
Console.Write("\nEnter Kilometres Travelled: ");
Then it asks this question a few times aswell
userInput = Console.ReadLine();
if (int.TryParse(userInput, out selection))
if (selection < minKms) {
//Deliver Error Message to user and redirect back to user input of kms
Console.WriteLine("\n Minimum Kms is {0:f2} Kilometres, Please Enter a value of {0:f2} or higher", minKms);
}
else {
inValid = false;
}
}
//return the KM Value
return selection;
}//End Input Kms
static double consumptionCalculation() {
int litres;
int kms;
double litresFormula;
double formulaResult;
//Define Base Varibles
formulaResult = 0.0;
litresFormula = 0.0;
litres = InputLitres();
kms = InputKM();
//Calculate fuel consumption in litres per 100km
litresFormula = (double)litres * 100;
formulaResult = (double)litresFormula / kms;
{
//Return the result value
return formulaResult;
}
}
//Print results method
static void PrintResults() {
double kmResult = consumptionCalculation();
Console.WriteLine("\n\n\tYour Fuel Consumption is {0} Litres per 100 Kilometres", kmResult);
}
//Start Program Loop Method
static void ProgramLoop() {
bool startAgain = true;
//Loop through each user Input Method
InputLitres();
InputKM();
consumptionCalculation();
PrintResults();
startAgain = DoItAgain();
}
static void Main(string[] args) {
WelcomeMessage();
ProgramLoop();
}
}
}
Can anyone give me an idea of where i am going wrong? I just need it to ask those questions once, return the value. Please make it simple as I am new to this. Thanks
This is the kind of thing you need to do.
void Main()
{
WelcomeMessage();
ProgramLoop();
}
static void ProgramLoop()
{
bool startAgain = true;
while (startAgain)
{
int litres = InputLitres();
int kms = InputKM(litres);
double consumption = consumptionCalculation(litres, kms);
PrintResults(consumption);
startAgain = DoItAgain();
}
}
static bool DoItAgain()
{
Console.Write("Start Over? (Y or N): ");
string reply = Console.ReadLine();
reply = reply.ToUpper();
return reply.ToUpper() == "Y";
}
static void WelcomeMessage()
{
Console.WriteLine("\n\n\tWelcome to the Fuel Consumption Calculator\n\n\t");
}
static int InputLitres()
{
int selection = -1;
int minLitres = 20;
bool invalid = true;
while (invalid)
{
Console.Write("\nEnter the amount of litres consumed: ");
if (int.TryParse(Console.ReadLine(), out selection))
{
invalid = selection < minLitres;
if (invalid)
{
Console.Write("\nPlease Enter an amount 20 litres or above\n\n Please Try Again:\n");
}
}
}
return selection;
}
static int InputKM(int litres)
{
int selection = -1;
int minKms = 8 * litres;
bool invalid = true;
while (invalid)
{
Console.Write("\nEnter Kilometres Travelled: ");
if (int.TryParse(Console.ReadLine(), out selection))
{
invalid = selection < minKms;
if (invalid)
{
Console.WriteLine("\nMinimum Kms is {0:f2} Kilometres, Please Enter a value of {0:f2} or higher", minKms);
}
}
}
return selection;
}
static double consumptionCalculation(int litres, int kms)
{
return (double)litres * 100.0 / (double)kms;
}
static void PrintResults(double consumption)
{
Console.WriteLine("\n\n\tYour Fuel Consumption is {0} Litres per 100 Kilometres", consumption);
}
Related
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 3 years ago.
Improve this question
using System;
namespace Test
{
class Program
{
static void Main(string[] args)
{
int num1 = int.Parse(args[0]);
int num2 = int.Parse(args[1]);
bool GameOver = false;
int turn = 3;
Random random = new Random();
int answer = random.Next(num1, num2);
// string input = "";
Console.WriteLine("Hello, welcome to the guess a number challenge");
while (!GameOver)
{
if (turn != 0)
{
turn--;
Console.WriteLine($"Please Select number between {num1} to {num2}:");
int SelectedNumber = int.Parse(Console.ReadLine());
if (SelectedNumber < answer && SelectedNumber >= num1)
{
System.Console.WriteLine("Almost there, just the number is too small\n");
} else if (SelectedNumber > answer && SelectedNumber <= num2)
{
System.Console.WriteLine("Your number is too big\n");
} else if(SelectedNumber == answer)
{
System.Console.WriteLine("CONGRATULATIONS!!!! You guess it right\n");
GameOver = true;
retry();
} else
{
System.Console.WriteLine("Your number is out of range\n");
}
} else
{
System.Console.WriteLine($"GAME OVER!!!! The answer is {answer}");
GameOver = true;
retry();
}
void retry() {
System.Console.WriteLine("Would you like to retry? Y/N");
string input = Console.ReadLine();
string ConsoleInput = input.ToLower();
if(ConsoleInput == "y")
{
GameOver = false;
turn = 3;
} else if(ConsoleInput == "n")
{
GameOver = true;
} else
{
Console.WriteLine("Invalid input");
retry();
}
}
}
}
}
}
Hello all, just want to ask a question.
I tried to build "guess a number" game in terminal, where player has to guess a number based on the number range given.
I tried to make the answer randomly generated, thus the Random class.
and the answer will be randomized after retry.
The problem is, after each retry, the answer is still the same.
I am not sure where did I did wrong.
Thanks for the help, and sorry for the noob question.
i edited out your code
using System;
namespace Test
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Enter num1");
int num1 = int.Parse(Console.ReadLine());
Console.WriteLine("Enter num2");
int num2 = int.Parse(Console.ReadLine());
bool GameOver = false;
int turn = 3;
Random random = new Random();
int answer = random.Next(num1, num2);
// string input = "";
Console.WriteLine("Hello, welcome to the guess a number challenge");
while (!GameOver)
{
if (turn != 0)
{
turn--;
Console.WriteLine($"Please Select number between {num1} to {num2}:");
int SelectedNumber = int.Parse(Console.ReadLine());
if (SelectedNumber < answer && SelectedNumber >= num1)
{
System.Console.WriteLine("Almost there, just the number is too small\n");
}
else if (SelectedNumber > answer && SelectedNumber <= num2)
{
System.Console.WriteLine("Your number is too big\n");
}
else if (SelectedNumber == answer)
{
System.Console.WriteLine("CONGRATULATIONS!!!! You guess it right\n");
GameOver = true;
retry();
}
else
{
System.Console.WriteLine("Your number is out of range\n");
}
}
else
{
System.Console.WriteLine($"GAME OVER!!!! The answer is {answer}");
GameOver = true;
retry();
}
void retry()
{
System.Console.WriteLine("Would you like to retry? Y/N");
string input = Console.ReadLine();
string ConsoleInput = input.ToLower();
if (ConsoleInput == "y")
{
answer = random.Next(num1, num2);
GameOver = false;
turn = 3;
}
else if (ConsoleInput == "n")
{
GameOver = true;
}
else
{
Console.WriteLine("Invalid input");
retry();
}
}
}
}
}
}
You need an outside loop in order to start a new game after the end:
See below a skeleton program with the necessary control flow.
class Program
{
static void Main(string[] args)
{
bool retry = false;
do
{
// start of game
bool gameOver = false;
int turn = 3;
do
{
// game here
// set gameOver when guess is corrent
turn--;
} while (turn>0 && !gameOver);
// post game scores
// ask to retry
} while (retry);
// end here
}
}
I have a simple console App that converts pounds to kilograms and vice-versa. What I'm attempting to do is if the user enters lb then run the function to convert pounds to kilograms, else if the user enters kg, then run the function to convert kilograms to pounds.
During the setup part of the condition in main, I get an error "Use of unassigned local variable 'lb'
...The Code (snippets):
//method to convert KG to Lbs
public void ConvertKg()
{
Console.WriteLine("C# KG to LB program\n");
Console.Write("Enter a number in KG: ");
double kilograms = Convert.ToDouble(Console.ReadLine());
double pounds = kilograms * 2.20462262185;
Console.WriteLine(kilograms + " kilograms is " + pounds + " pounds");
}
//method to convert Lbs to KG
public void ConvertLb()
{
Console.WriteLine("C# LB to KG program\n");
Console.Write("Enter a number in lbs:");
double pounds_userEntry = Convert.ToDouble(Console.ReadLine());
double kilogram_userEntry = pounds_userEntry * 0.453592;
Console.WriteLine(kilogram_userEntry + " kilograms is " + pounds_userEntry + " pounds");
}
...main:
string lb, kg;
string userInput = "";
Console.Write("Enter either lb or kg:");
if(userInput == lb) // where the error occurs
{
var k = new ConvertNumber();
k.ConvertLb();
}
else
{
var l = new ConvertNumber();
l.ConvertKg();
}
Console.ReadLine();
...the problem seems to be within the approach I'm using to set up the conditional statement to accept the user's input. ...could I get some help as to what I'm doing wrong?
There is no need to do string lb, kg;, so you can leave it out.
userInput is assigned to "", but it should probably contain something from the user.
Replace
string userInput = "";
with
Console.Write("Enter either kg or lb: ");
string userInput = Console.ReadLine() // Console.ReadLine enables the user to type some text and returns it
Because
Console.Write("Enter either kg or lb");
has been done now, you can leave it out afterwards.
Now you can compare userInput with "lb" and "kg".
Replace
if(userInput == lb)
{
var k = new ConvertNumber();
k.ConvertLb();
}
else
{
var l = new ConvertNumber();
l.ConvertKg();
}
Console.ReadLine();
with
if (userInput == "lb") {
ConvertLb();
} else if (userInput == "kg") {
ConvertKg();
} else {
Console.WriteLine("Your input was neither lb nor kg");
}
Final code (main):
Console.Write("Enter either kg or lb: ");
string userInput = Console.ReadLine() // Console.ReadLine enables the user to type some text and returns it
if (userInput == "lb") { // The user typed "lb"
ConvertLb();
} else if (userInput == "kg") { // The user typed "kg"
ConvertKg();
} else { // The user typed neither "lb" nor "kg"
Console.WriteLine("Your input was neither lb nor kg");
}
As the comments are mentioning, you have to either initialize the lb variable with "lb" or to compare the userInput directly to the string "lb" as Rakesh is writing in comments.
Also I've seen that you don't read the user input.
Below I've created a quick sample code that should do the job that you expect and should be easy to understand.
class Program
{
public const string Lb = "lb"; //User options as constants
public const string Kg = "kg";
static void Main(string[] args)
{
string userInput = GetUserInput();
try
{
ConvertUserInput(userInput);
}
catch (ArgumentException ex)
{
Console.WriteLine(ex.Message); // Show error message
userInput = GetUserInput(); // Get user input again
ConvertUserInput(userInput);
}
Console.ReadLine();
}
private static string GetUserInput()
{
Console.Write("Enter either lb or kg:");
string userInput = Console.ReadLine();
return userInput;
}
private static void ConvertUserInput(string userInput)
{
// Guard for throwing an error when the user enters another value
if (!IsValidUserInput(userInput))
throw new ArgumentException("Input value is not lb or kg");
if (ConvertFromPoundsToKg(userInput)) // where the error occurs
{
var k = new ConvertNumber();
k.ConvertLb();
}
else
{
var l = new ConvertNumber();
l.ConvertKg();
}
}
/// <summary>
/// userInput is either "lb" or "kg"
/// </summary>
/// <param name="userInput"></param>
/// <returns></returns>
private static bool IsValidUserInput(string userInput)
{
return ConvertFromPoundsToKg(userInput) || (ConvertFromKgToPounds(userInput));
}
private static bool ConvertFromKgToPounds(string userInput)
{
return userInput == Kg;
}
private static bool ConvertFromPoundsToKg(string userInput)
{
return userInput == Lb;
}
}
The problem is that the variable lb is not initialized. It doesn't have a value that you could compare against. I've changed your code to solve this problem. Next steps would be to get the "number" the user entered before the unit and pass it to a unit coversion function and output it to the user again. This will be left for you to do ;)
class Program
{
static void Main(string[] args)
{
//string lb, kg;
//string userInput = "";
Console.Write("Enter either lb or kg:");
string input = Console.ReadLine();
string unit = input.Substring(input.Length-2);
if (unit == "lb") // where the error occurs
{
int k = ConvertNumber();
Console.WriteLine(k + "kg");
//k.ConvertLb();
}
else if (unit == "kg")
{
int l = ConvertNumber();
Console.WriteLine(l + "lb");
//l.ConvertKg();
}
else
{
Console.WriteLine("invalid unit");
}
Console.ReadLine();
}
static int ConvertNumber()
{
Console.WriteLine("convert");
return 123;
}
}
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 5 years ago.
Improve this question
How do I get out of this loop?
I wrote a program that checks to see if corresponding places in the numbers are the same total. The console output should be true or false. I wrote that, and then added the top part that interacts with the user, and now I get stuck in a loop. How do I get out of it?
using System;
namespace DeliverablePart1
{
class DeliverablePart1
{
static void Main(string[] args)
{
string gameAnswer;
bool repeat1 = true, repeat2 = true;
while (repeat1 == true)
{
repeat2 = true;
Console.WriteLine("Would you like to compare 2 numbers to see if their corresponding place is same total?");
gameAnswer = Console.ReadLine();
while (repeat2 == true)
{
if (gameAnswer == "yes" || gameAnswer == "yes" || gameAnswer == "YES")
{
Console.WriteLine("Please enter a three digit whole number");
string firstValue = Console.ReadLine();
int firstNumber = ValidInteger(firstValue);
Console.WriteLine("Please enter a second three digit whole number");
string secondValue = Console.ReadLine();
int secondNumber = ValidInteger(secondValue);
repeat1 = false;
repeat2 = false;
}
else if (gameAnswer == "no" || gameAnswer == "No" || gameAnswer == "NO")
{
Console.WriteLine("Okay, exiting now");
repeat1 = false;
repeat2 = false;
}
else
{
Console.WriteLine("I do not understnad what you have said");
repeat2 = false;
}
void Add(int firstNumber, int secondNumber)
{
int length1 = firstNumber.ToString().Length;
int length2 = secondNumber.ToString().Length;
string userInput;
if (length1 == length2)
{
string Answer = Convert.ToString(Compare(firstNumber, secondNumber, length1));
}
else
{
userInput = "invalid user input - Check number of digits next time.";
Console.WriteLine(userInput);
Console.ReadKey();
}
Console.ReadKey();
}
int ValidInteger(string digit1)
{
int value = 0;
string notInt = "This is not an integer.";
{
bool successfullyParsed = int.TryParse(digit1, out value);
if (successfullyParsed)
{
int firstNumber = Convert.ToInt32(value);
return value;
}
else
{
Console.WriteLine(notInt);
Console.ReadKey();
Environment.Exit(0);
return value;
}
}
}
string Compare(int a, int b, int c)
{
int lastDigitA;
int lastDigitB;
lastDigitA = (a % 10);
lastDigitB = (b % 10);
int sumStatic = lastDigitA + lastDigitB;
do
{
lastDigitA = (a % 10);
lastDigitB = (b % 10);
a = a / 10;
b = b / 10;
c--;
int sumCompare = lastDigitA + lastDigitB;
if (sumCompare != sumStatic)
{
Console.WriteLine("False");
return "False";
}
}
while (c != 0);
Console.WriteLine("True");
return "True";
}
}
}
}
}
}
From my understanding, it looks like you want the user to enter in three ints (with some input validation), and put the three ints through the Compare() function. If the function returns true, then say "True" to the console, and if it's false then say "False" to the console. If that's the case, I refactored your code into this (and it doesn't get stuck in a loop):
using System;
namespace DeliverablePart1
{
internal class DeliverablePart1
{
private static void Main(string[] args)
{
Console.WriteLine("Would you like to compare 2 numbers to see if their corresponding place is same total?");
var shouldContinue = Console.ReadLine();
if (shouldContinue != null && shouldContinue.Equals("yes", StringComparison.CurrentCultureIgnoreCase))
{
var firstNum = GetIntFromUser("Please enter a three digit whole number");
var secondNum = GetIntFromUser("Please enter a three digit whole number");
var thirdNum = GetIntFromUser("Please enter a three digit whole number");
Console.WriteLine(Compare(firstNum, secondNum, thirdNum) ? "True" : "False");
}
else
{
Console.WriteLine("Exiting");
}
// waits for the user to press a key to exit the app, so that they can see their result
Console.ReadKey();
}
/// <summary>
/// Makes the user enter in a three digit number, and exits if they say "no"
/// </summary>
/// <param name="msg">The message prompt to ask for the integer</param>
/// <returns>System.Int32., or will exit</returns>
public static int GetIntFromUser(string msg)
{
while (true)
{
Console.WriteLine(msg);
var valFromUser = Console.ReadLine()?.Trim();
if (valFromUser != null)
{
int result;
if (int.TryParse(valFromUser.Trim(), out result) && valFromUser.Length == 3)
{
return result;
}
if (valFromUser.Equals("no", StringComparison.CurrentCultureIgnoreCase))
{
Console.WriteLine("Exiting.");
Environment.Exit(0);
}
}
Console.WriteLine("Hmm, that's not a three digit number. Try again.");
}
}
public static bool Compare(int a, int b, int c)
{
var lastDigitA = a % 10;
var lastDigitB = b % 10;
var sumStatic = lastDigitA + lastDigitB;
do
{
lastDigitA = a % 10;
lastDigitB = b % 10;
a = a / 10;
b = b / 10;
c--;
var sumCompare = lastDigitA + lastDigitB;
if (sumCompare != sumStatic)
{
return false;
}
} while (c != 0);
return true;
}
}
}
I am creating a random number guessing game where the user sets the maximum number they want to guess from. I have figured out most of the code, the problem that I seem to be getting is that after setting the maximum number and beginning to guess the answer is always 0. Any tips on how to adjust my code so that the answer is a number within the range and not 0?
class Program
{
public static int SelectedNumber = 0;
public static Random ran = new Random();
public static bool GameOver = false;
public static int UserMaxValue = 0;
public static string decision;
static void Main(string[] args)
{
int UserNumber;
SelectedNumber = ran.Next(0, UserMaxValue);
do
{
Console.WriteLine("What is the maximum number you want to guess from?");
UserMaxValue = Convert.ToInt32(Console.ReadLine());
do
{
Console.WriteLine("Select a number between 1 and {0}!", UserMaxValue);
UserNumber = Convert.ToInt32(Console.ReadLine());
GuessNumber(UserNumber);
} while (GameOver == false);
} while (GameOver == false);
}
public static void GuessNumber(int UserNumber)
{
if (UserNumber < SelectedNumber)
Console.WriteLine("Your number is wrong, please try again!");
else if (UserNumber > SelectedNumber)
Console.WriteLine("Your Number is wrong, please try again!");
//else if (UserNumber == 0)
// Console.WriteLine("Your Number is wrong, please try again!");
else
{
Console.WriteLine("Yay! You got the right number. Do you want to play again? (y/n) ", decision);
decision = Console.ReadLine();
if (decision == "n")
GameOver = true;
else
do
{
Console.WriteLine("What is the maximum number you want to guess from?");
UserMaxValue = Convert.ToInt32(Console.ReadLine());
do
{
Console.WriteLine("Select a number between 1 and {0}!", UserMaxValue);
UserNumber = Convert.ToInt32(Console.ReadLine());
GuessNumber(UserNumber);
} while (GameOver == false);
} while (GameOver == false);
}
}
}
}
You have the following lines, in this order (I'm omitting the rest in between):
public static int UserMaxValue = 0;
// ...
SelectedNumber = ran.Next(0, UserMaxValue);
// ...
Console.WriteLine("What is the maximum number you want to guess from?");
UserMaxValue = Convert.ToInt32(Console.ReadLine());
You have to ask the user for UserMaxValue before you can correctly set SelectedNumber.
Had to do some corrections on your code. Added some comments for the changes.
You better add error handling on the user input.
UPDATE: Added error handling for invalid input.
class Program
{
public static int SelectedNumber = 0;
public static Random ran = new Random();
public static bool GameOver = false;
public static int UserMaxValue = 0;
static void Main(string[] args)
{
int UserNumber = 0;
bool playAgain = false;
do
{
bool isUserMaxValueValid = false;
do
{
Console.WriteLine("What is the maximum number you want to guess from?");
isUserMaxValueValid = int.TryParse(Console.ReadLine(), out UserMaxValue);
} while (!isUserMaxValueValid);
SelectedNumber = ran.Next(1, UserMaxValue); // Re-assign SelectedNumber for every new max number input. Random number start changed to 1 to avoid 0 value for SelectedNumber
do
{
bool isUserNumberValid = false;
do
{
Console.WriteLine("Select a number between 1 and {0}!", UserMaxValue);
isUserNumberValid = int.TryParse(Console.ReadLine(), out UserNumber);
} while (!isUserNumberValid);
playAgain = GuessNumber(UserNumber);
// I changed GameOver to see if the guessing portion is finished or not
} while (!GameOver); // You don't need to use GameOver == false
} while (playAgain); // Check if user wants to play again or not
}
public static bool GuessNumber(int UserNumber)
{
if (UserNumber != SelectedNumber)
{
GameOver = false;
Console.WriteLine("Your number is wrong, please try again!");
}
else
{
GameOver = true;
bool isPlayAgainValid = false;
Console.WriteLine("Yay! You got the right number. Do you want to play again? (y/n)");
do
{
string decision = Console.ReadLine();
if (decision.Equals("n", StringComparison.InvariantCultureIgnoreCase))
{
return false;
}
else if (decision.Equals("y", StringComparison.InvariantCultureIgnoreCase))
{
break;
}
if(!isPlayAgainValid)
{
Console.WriteLine("Please enter y or n only.");
}
} while (!isPlayAgainValid);
// I removed redundant code
}
return true;
}
}
I have a few problems with the code below. I'm still learning and I don't know how to fix it.
1 .-What I'm trying to do is create a method (GetInt) to store variables like I'm trying to do in the second method (GetTrack) that will go into my main method.
2.-I can't get the GetInt method to loop when theres an invalid input, I'm guessing there's something wrong with the try/catch and boolean thingy
Thank you
//Get int Method
static public void GetInt(string sPrompt, int iMin, int iMax)
{
int iNum;
bool bError = false;
do
{
bError = true;
try
{
Console.Write(sPrompt);
iNum = int.Parse(Console.ReadLine());
if ((iNum < iMin) || (iNum > iMax))
{
Console.WriteLine("The value is out of range.");
bError = true;
}
}
catch (ArgumentException)
{
Console.WriteLine("An invalid number was entered, please try again.");
bError = true;
}
}
while (bError == false);
}
//Get Track Method
static public void GetTrack()
{
int iMin;
int iSec;
iMin = GetInt("Enter the minutes: ", 0, 10);
iSec = GetInt("Enter the seconds: ", 0, 59);
}
Immediately in the beginning of GetInt you set bError to true. This most likely should be false so you would actually loop since nowhere do you set it to false.
Also you don't return anything from the method so you don't get anything back. You have to change the method to return int and actually return the value when you get it.
The declaration of your GetInt method should be changed to the following:
//Get int Method
static public int GetInt(string sPrompt, int iMin, int iMax)
Remove the bError = true; statement from the beginning of your do...while loop.
After your do...while loop, add the following statement:
return iNum;
Also, your while condition should be changed from bError == false to bError == true or simply to bError, which means the same thing, if your intent is to keep prompting the user until the input is acceptable.
Here is how I "get" user input from the console:
string choice = string.Empty;
bool goodChoice = false;
while (!goodChoice)
{
Console.Clear();
Console.WriteLine(string.Empty);
Console.WriteLine("Do you really want to hurt me?");
Console.WriteLine(string.Empty);
Console.WriteLine(string.Empty);
Console.WriteLine("Please Y or N (or 0 to exit)");
choice = Console.ReadLine().Trim();
if (choice.Equals("Y", StringComparison.OrdinalIgnoreCase))
{
goodChoice = true;
}
if (choice.Equals("N", StringComparison.OrdinalIgnoreCase))
{
goodChoice = true;
}
if (choice.Equals("0"))
{
goodChoice = true;
return; /* exist the routine */
}
}
Modified for your case
string choice = string.Empty;
bool goodChoice = false;
while (!goodChoice)
{
Console.Clear();
Console.WriteLine(string.Empty);
Console.WriteLine("Enter an Integer between {0} and {1}", minValue, maxValue);
Console.WriteLine(string.Empty);
Console.WriteLine(string.Empty);
Console.WriteLine("Please enter an integer (or X to exit)");
choice = Console.ReadLine().Trim();
int intParseResult = 0;
bool intParseAttempt = int.TryParse(choice, out intParseResult);
if(!intParseAttempt)
{
goodChoice = false;
}
else
{
if ((intParseResult < minValue) || (intParseResult > maxValue))
{
Console.WriteLine("Out of Range");
}
else
{
goodChoice = true;
}
}
if (choice.Equals("X"))
{
goodChoice = true;
return -99999; /* you'll have to figure out how to handle exits on your own */
}
}