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 */
}
}
Related
i'm new at coding C# pls help me fix this simple dice game, it keeps on looping at the end of the game
** apparently how i think is that in the end of this code something makes the NO commend on looping and getting re runed**
using System;
namespace first_game
{
class Program
{
static void Main(string[] args)
{
string userName;
userName = Console.ReadLine();
#region
{
int userPoint = 0;
int cpuPoint = 0;
int pDice;
bool closeApp;
while (true)
{
while (cpuPoint < 10 && userPoint < 10)
{
Random rd = new Random();
pDice = rd.Next(1, 6);
#endregion
int P2Dice;
Random scondRd = new Random();
P2Dice = scondRd.Next(1, 6);
Console.ReadLine();
Console.WriteLine("-------------------");
Console.Write("playe dice:");
Console.WriteLine(pDice);
Console.Write("CPU dice:");
Console.WriteLine(P2Dice);
Console.ReadLine();
if (pDice > P2Dice)
{
userPoint = userPoint + 1;
}
else if (pDice < P2Dice)
{
cpuPoint = cpuPoint + 1;
}
Console.Clear();
Console.WriteLine(userName);
Console.Write("player point:");
Console.WriteLine(userPoint);
Console.Write("CPU point:");
Console.Write(cpuPoint);
Console.ReadLine();
}
if (userPoint == 10)
{
Console.WriteLine("-----------------\nYOU WIN!!!");
Console.ReadLine();
}
else
{
Console.WriteLine("-----------------\nYOU lost!!! LOL");
Console.ReadLine();
}
Console.WriteLine("wanna continue?\n press Y for yes press N for NO");
ConsoleKeyInfo sw;
sw = Console.ReadKey();
Console.Clear();
if (sw.Key == ConsoleKey.Y)
{
userPoint = 0;
cpuPoint = 0;
continue;
}
else if (sw.Key == ConsoleKey.N)
{
}
else
Console.WriteLine("ERROR!");
}
}
}
}
}
You seem to have the wrong idea about continue. A while loop always (given a true condition) reruns if it reaches the end, a continue just starts the next iteration early.
else if (sw.Key == ConsoleKey.N) { }
else Console.WriteLine("ERROR!");
This is where you should exit the loop, for example using a break
else if (sw.Key == ConsoleKey.N) {
break;
} else Console.WriteLine("ERROR!");
Add a break to exit the while loop:
if (userPoint == 10)
{
Console.WriteLine("-----------------\nYOU WIN!!!");
break;
}
else
{
Console.WriteLine("-----------------\nYOU lost!!! LOL");
break;
}
Then add this after the while loop, so that the console doesn't close:
Console.ReadLine();
I need to ask the user for his name, surname and other details and I wan't to verify them, basically checking if the string is empty, is an integer, or contains an integer. The problem with this code is let's say I type in "a" it works. And if I type in a2 it shows the correct error message but when I go to type in "a" on its own it keeps repeating the same error message. Any help would be appreciated and a cleaner way to write this would also be appreciated as I have to do this for the surname, email and other fields.
bool check = true;
Console.Write("Enter your name:");
string name = Console.ReadLine();
bool isEmpty = string.IsNullOrEmpty(name);
bool isIntString = name.All(char.IsDigit);
bool containsInt = name.Any(char.IsDigit);
while (check == true) {
if (isEmpty)
{
Console.WriteLine("Name cannot be empty");
Console.Write("Enter your name: ");
name = Console.ReadLine();
}
else if(isIntString)
{
Console.WriteLine("Your name cannot be made up of numbers");
Console.Write("Enter your name: ");
name = Console.ReadLine();
}
else if (containsInt)
{
Console.WriteLine("Your name cannot contain numbers");
Console.Write("Enter your name: ");
name = Console.ReadLine();
}
else if(!isEmpty && !isIntString && !containsInt)
{
check = false;
Console.WriteLine("Name filled");
}
}
Console.WriteLine("Your name is: " + name);
Console.ReadKey();
After reading the input, you are checking for null/empty/integers.
bool isEmpty = string.IsNullOrEmpty(name);
bool isIntString = name.All(char.IsDigit);
bool containsInt = name.Any(char.IsDigit);
However, these checks are placed outside the loop. Once evaluated, the 3 verification variables never changes, even after new input has been read.
For fixing the same, you need to place the checks within the loop.
while (check == true) {
bool isEmpty = string.IsNullOrEmpty(name);
bool isIntString = name.All(char.IsDigit);
bool containsInt = name.Any(char.IsDigit);
// rest of code
To clean up code, you could refactor out the expressions and reading input to create a pattern, which could be reused for other inputs. For example,
void Main()
{
bool check = true;
var name = ReadInput("Enter your name:",ValidationExpressionsForName);
// var surname = ReadInput("Enter your SurName :",ValidationExpressionsForSurName);
// so on
Console.WriteLine("Your name is: " + name);
}
public string ReadInput(string inputMessage,Func<string,IEnumerable<EvaluationExpression>> evaluationExpression)
{
while (true)
{
Console.Write(inputMessage);
string term = Console.ReadLine();
if(evaluationExpression(term).Any(x=>x.Expression()))
{
Console.WriteLine(evaluationExpression(term).First(x=>x.Expression()).Message);
}
else
return term;
}
}
public IEnumerable<EvaluationExpression> ValidationExpressionsForName(string message) => new EvaluationExpression[]
{
new EvaluationExpression{ Expression = ()=>String.IsNullOrWhiteSpace(message), Message= "Name cannot be empty"},
new EvaluationExpression{ Expression = ()=>message.All(char.IsDigit),Message ="Your name cannot be made up of numbers"},
new EvaluationExpression{ Expression = ()=>message.Any(char.IsDigit),Message="Your name cannot contain numbers"}
};
public class EvaluationExpression
{
public Func<bool> Expression{get;set;}
public string Message{get;set;}
}
Checking if a string is Null, Empty or WhiteSpace is relatively easy:
https://learn.microsoft.com/en-us/dotnet/api/system.string.isnullorwhitespace
Checking if it is a Number can be done. Just feed it to Int32.TryParse() and see if it can make sense of the input.
If it contains a anumber? Checkable, but not easily. You could itterate over all Characters in the string and check if any of them parse to Int. Note that this cheeck would supersede/make unessesary the previous check too. I made it into a simple function:
public bool IsValidName(String input){
if(String.IsNullOrWhiteSpace(input)){
return false;
}
foreach (char current in input){
int ignore;
//TryPrase will not take Chars, but turning it into a string should be this easy
String currentString = current.ToString();
if(Int32.TryParse(currentString, out ignore))
return false;
}
//You only get here if none of hte false cases was trigerred
return true;
}
All of this might be solveable with a single Regular Expression too, but I am not that good at Regex.
With small changes to your code:
string name;
while (true)
{
Console.Write("Enter your name:");
name = Console.ReadLine();
bool isEmpty = string.IsNullOrEmpty(name);
bool isIntString = name.All(char.IsDigit);
bool containsInt = name.Any(char.IsDigit);
if (isEmpty)
{
Console.WriteLine("Name cannot be empty");
}
else if (isIntString)
{
Console.WriteLine("Your name cannot be made up of numbers");
}
else if (containsInt)
{
Console.WriteLine("Your name cannot contain numbers");
}
else
{
Console.WriteLine("Name filled");
break;
}
}
Console.WriteLine("Your name is: " + name);
Console.ReadKey();
With variable term:
static string GetUserInput(string term)
{
string name;
while (true)
{
Console.Write($"Enter your {term}:");
name = Console.ReadLine();
bool isEmpty = string.IsNullOrEmpty(name);
bool isIntString = name.All(char.IsDigit);
bool containsInt = name.Any(char.IsDigit);
if (isEmpty)
{
Console.WriteLine("Cannot be empty");
}
else if (isIntString)
{
Console.WriteLine("Cannot be made up of numbers");
}
else if (containsInt)
{
Console.WriteLine("Cannot contain numbers");
}
else
{
Console.WriteLine($"Your {term} filled");
break;
}
}
Console.WriteLine($"Your {term} is: {name}");
return name;
}
Your code fails here. It goes into this else block displays the error message and then reads from the console again. while check still being true and isIntString still true it again lands up in this block. You need to correct it for all the three checks you have placed on the the string.
else if(isIntString)
{
Console.WriteLine("Your name cannot be made up of numbers");
isIntString = false; // to prevent going into this block again
Console.Write("Enter your name: ");
name = Console.ReadLine();
}
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;
}
}
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);
}