C# how to set a conditional statement to except user input? - c#

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;
}
}

Related

Checking whether string is empty, contains int or is an integer

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();
}

In and Out in C# Console Application

If I enter "01" it will output "IN" and if I input "01" again it will out but the problem is I need to OUT the first number I enter before I can IN another number. Can someone help me????
class Program
{
static string [] num = {"01","02","03"};
static string en;
static string en1;
static void Main()
{
while (true)
{
Console.Clear();
Console.Write("Enter your code: ");
en = Console.ReadLine();
for (int i = 0; i < num.Length; i++)
if (en == num[i])
{
Console.Write("In");
Console.ReadLine();
Console.Clear();
Console.Write("Enter your code: ");
en1 = Console.ReadLine();
if (en1 == en)
{
Console.Write("Out");
Console.ReadLine();
Main();
}
}
}
}
}
Tried to keep it simple to follow, if you're confused by any part please ask
class Program
{
static List<string> num = new List<string> (){ "01", "02", "03" };
static string en;
static string en1;
static void Main()
{
while (true) {
Console.Write("Enter your code: ");
if (String.IsNullOrEmpty(en)) { //check en isn't set yet
en = Console.ReadLine(); // set en
if (num.Contains(en)){ // if en exists in the num list proceed
Console.WriteLine("IN");
} else {
en = null; //if it doesn't null it and start again
}
} else {
en1 = Console.ReadLine(); //read in the value to compare
if (en == en1) { //compare the original input to this
en = null; //if they're the same, null the original
Console.WriteLine("OUT");
}
}
}
}
}

How To Display That an Array is Full

I am working on a simple code that asks for the name, age, and gender of at most 5 patients. After each patient, it should ask to input another patient or return to main menu. Once 5 have been input into an array, there should be a prompt to the user that the array is full.
My problem is the code asks for name,age and gender 5 times upfront, and does not give any indication the array is full. How would I change the code to reflect that and still save the inputs? (Code below).
class MainClass
{
enum Gender { female, male }
struct Record
{
public string _Name;
public int _Age;
public Gender _Gender;
}
public static void Main(string[] args)
{
//title
Console.Write("\t\t\t\t\tPatient Records\n");
string selection = "";
Record[] patients = new Record[5];
GetRecords(patients);
Console.Write("a. Add\n d.Display\ns. Stats\nq. Quit");
Console.Write("Your selection: ");
selection = Console.ReadLine();
switch (selection)
{
case "a":
GetRecords(patients);
break;
case "d":
break;
case "s":
Stats(patients);
break;
case "q":
//CUtility.Pause();
break;
}
}
static void GetRecords(Record[] patient_rec)
{
for (int i = 0; i < patient_rec.Length; i++)
{
Console.Write("Enter your age: ");
int.TryParse(Console.ReadLine(), out patient_rec[i]._Age);
Console.Write("Enter your name: ");
patient_rec[i]._Name = Console.ReadLine();
Console.Write("Enter your gender (female or male): ");
Gender.TryParse(Console.ReadLine(), out patient_rec[i]._Gender);
}
}
static void Stats(Record[]patient_rec)
{
}
}
I would suggest trying to make your code a little easier to read - and more robust.
Try this:
static void GetRecords(Record[] patient_rec)
{
for (int i = 0; i < patient_rec.Length; i++)
{
Console.WriteLine("Record {0} of {1} entry", i + 1, patient_rec.Length);
patient_rec[i] = new Record()
{
_Age = AskInteger("Enter your age: "),
_Name = AskString("Enter your name: "),
_Gender = AskGender("Enter your gender (female or male): "),
};
string ask = "";
while (string.IsNullOrEmpty(ask) || (ask.ToLower()[0] != 'y' && ask.ToLower()[0] != 'n'))
{
Console.WriteLine("Continue? yes or no (then hit enter)");
ask = Console.ReadLine();
}
if (ask.ToLower()[0] == 'y')
{
continue;
}
break;
}
Console.WriteLine("Thank you. Input completed.");
}
To make this work you need these three input functions:
private static int AskInteger(string message)
{
int result;
Console.WriteLine(message);
string input = Console.ReadLine();
while (!int.TryParse(input, out result))
{
Console.WriteLine("Invalid input.");
Console.WriteLine(message);
input = Console.ReadLine();
}
return result;
}
private static string AskString(string message)
{
Console.WriteLine(message);
string input = Console.ReadLine();
while (string.IsNullOrWhiteSpace(input))
{
Console.WriteLine("Invalid input.");
Console.WriteLine(message);
input = Console.ReadLine();
}
return input;
}
private static Gender AskGender(string message)
{
Gender result;
Console.WriteLine(message);
string input = Console.ReadLine();
while (!Gender.TryParse(input, out result))
{
Console.WriteLine("Invalid input.");
Console.WriteLine(message);
input = Console.ReadLine();
}
return result;
}
Your loop is only set to go to the size of the array, so logically you could show a message after the loop (this will get hit when the loop finishes).
If you were controlling your array access in a while loop then just compare your indexer i to the length of the array (patient_rec.Length), if it equals or exceeds the length then show the message.
I would do it in a simpler way:
enum Gender { female, male }
struct Record
{
public string _Name;
public int _Age;
public Gender _Gender;
}
static void Main(string[] args)
{
//title
Console.Write("\t\t\t\t\tPatient Records\n");
IList<Record> patients = GetRecords(5);
SchedulePatients(patients);
}
static void SchedulePatients(IList<Record> patients)
{
Console.Write("a. Add\n d.Display\ns. Stats\nq. Quit");
Console.Write("Your selection: ");
string selection = Console.ReadLine();
switch (selection)
{
case "a":
patients.Add(GetRecord());
SchedulePatients(patients);
break;
case "d":
break;
case "s":
Stats(patients);
break;
case "q":
//CUtility.Pause();
break;
}
}
static IList<Record> GetRecords(int amount)
{
IList<Record> patients = new List<Record>();
for (int i = 0; i < amount; i++)
{
patients.Add(GetRecord());
}
return patients;
}
static Record GetRecord()
{
Record patient = new Record();
Console.Write("Enter your age: ");
int.TryParse(Console.ReadLine(), out patient._Age);
Console.Write("Enter your name: ");
patient._Name = Console.ReadLine();
Console.Write("Enter your gender (female or male): ");
Enum.TryParse(Console.ReadLine(), out patient._Gender);
return patient;
}
static void Stats(IList<Record> patients)
{
foreach (var patient in patients)
{
Console.WriteLine(string.Concat("Name: ", patient._Name, " Age: ", patient._Age, " Gender: ", patient._Gender));
}
Console.ReadLine();
}
}
If you would like to meet the requirements with the smallest change possible, you just need to add the bit about prompting the user.
static void GetRecords(Record[] patient_rec)
{
for (int i = 0; i < patient_rec.Length; i++)
{
Console.Write("Enter your age: ");
int.TryParse(Console.ReadLine(), out patient_rec[i]._Age);
Console.Write("Enter your name: ");
patient_rec[i]._Name = Console.ReadLine();
Console.Write("Enter your gender (female or male): ");
Gender.TryParse(Console.ReadLine(), out patient_rec[i]._Gender);
Console.Write("Enter another (Y/N)? ");
var s = Console.ReadLine();
if (s.ToUpper() != "Y") return;
}
Console.WriteLine("You've entered the maximum number of records.");
}

How to make number Count in loop in c#?

This is a simple begginer program with setter and getter concept
now i have to make it to first enter user name and password to get welcomed
and IF I ENTER WRONG INFO IT SHOULD DISPLAY INVALID AND 5 TRIES LEFT THEN if i again enter wrong info it should display 4 tries left and so on and finally when all tries are over it should hang the program or lock the screen or so
using System;
namespace ConsoleApplication4
{
class Program
{
static void Main(string[] args)
{
demo obj = new demo();
string uname, pass;
Console.ForegroundColor = ConsoleColor.Green;
label1:
Console.Clear();
Console.WriteLine("Enter username");
uname = Console.ReadLine();
Console.WriteLine("Enter Password");
pass = Console.ReadLine();
obj.setName(uname);
obj.setPass(pass);
if (obj.getName() == "niit")
{
if (obj.getPass() == "1234")
{
Console.WriteLine("welcome");
}
}
else
{
Console.Clear();
Console.WriteLine("Invalid");
Console.WriteLine("\n \n \n To try again enter y");
int n = 5;
string yes = Console.ReadLine();
if (yes == "y")
{
while (n >= 1)
{
Console.Write(n + " Tries left");
goto label1;
n = --n;
}
}
}
Console.ReadKey();
}
}
class demo
{
private string name, pass;
public void setName(string name)
{
this.name = name;
}
public string getName()
{
return name;
}
public void setPass(string pass)
{
this.pass = pass;
}
public string getPass()
{
return pass;
}
}
}
Please suggest a simple begginers code to make the loop work and make the count down
A while loop should suffice. Using a boolean to detect successful password entry.
When entered, it will break out of the loop.
invalid attempts will decrement the AttemptsLeft int.
Note: I haven't tried this in Visual Studio, the logic should be sound, but I recommend debugging and stepping through it to test if it meets your criteria.
static void Main(string[] args)
{
demo obj = new demo();
string uname, pass;
Console.ForegroundColor = ConsoleColor.Green;
label1:
Console.Clear();
Console.WriteLine("Enter username");
uname = Console.ReadLine();
Console.WriteLine("Enter Password");
bool SuccessfulPassword = false;
int AttemptsLeft = 5;
while(!SuccessfulPassword && AttemptsLeft > 0){
pass = Console.ReadLine();
obj.setName(uname);
obj.setPass(pass);
if (obj.getName() == "niit")
{
if (obj.getPass() == "1234")
{
Console.WriteLine("welcome");
SuccessfulPassword = true;
}
}
else
{
AttemptsLeft--;
Console.Clear();
Console.WriteLine("Invalid");
Console.WriteLine("\n \n \n To try again enter y");
int n = 5;
string yes = Console.ReadLine();
if (yes == "y")
{
Console.Write(AttemptsLeft + " Tries left");
}
}
Console.ReadKey();
}
}
try this updated main method:
static void Main(string[] args)
{
demo obj = new demo();
int n = 5;
string uname, pass;
Console.ForegroundColor = ConsoleColor.Green;
//Console.Clear();
label1:
Console.WriteLine("\n");
Console.WriteLine("Enter username");
uname = Console.ReadLine();
Console.WriteLine("Enter Password");
pass = Console.ReadLine();
obj.setName(uname);
obj.setPass(pass);
if (obj.getName() == "niit" && obj.getPass() == "1234")
{
Console.WriteLine("welcome");
}
else
{
//Console.Clear();
if (n < 1)
{
//Add ur screenlock n hang prog code
Console.Clear();
Console.WriteLine("ScreenLock");
}
else
{
Console.WriteLine("\n Invalid");
Console.WriteLine("\n To try again enter y");
string yes = Console.ReadLine();
Console.WriteLine("\n");
if (yes == "y")
{
while (n >= 1)
{
Console.Write(n + " Tries left");
n = --n;
goto label1;
}
}
}
}
Console.ReadKey();
}
namespace ConsoleApplication4
{
class Program
{
static void Main(string[] args)
{
demo obj = new demo();
string uname, pass;
boolean successful = false;
int32 tries = 5;
Console.ForegroundColor = ConsoleColor.Green;
label1:
Do
{
Console.Clear();
Console.WriteLine("Enter username");
uname = Console.ReadLine();
Console.WriteLine("Enter Password");
pass = Console.ReadLine();
obj.setName(uname);
obj.setPass(pass);
if (obj.getName() == "niit")
{
if (obj.getPass() == "1234")
{
Console.WriteLine("welcome");
successful = true;
}
}
if (!successful)
{
tries--;
Console.Clear();
Console.WriteLine("Invalid");
if (tries > 1)
{
Console.WriteLine("Have " + tries + " attempts left");
}
ElseIf (tries == 1)
{
Console.WriteLine("Have only one more attempt left");
}
Else
{
Console.WriteLine("Maximum number of tries exceed");
Console.WriteLine("Goodbye");
}
}
} While(!successful && Tries > 0);
}
}
Everytime you get the wrong input, you remaking your count int n = 5;
so everytime you have 5 tries left.
What you can do is to declare your count outside of the static void Main(string args[]) method
just like:
int n =5;
static void Main(string args[])
{
}
you problems are the following nested if-contitions
if (obj.getName() == "niit")
{
if (obj.getPass() == "1234")
{
Console.WriteLine("welcome");
}
}
else
{
\\...
}
If the username is correct and the pass not, it wont enter the else branch.
a better solution to ask for input until it is valid id a do ... while loop
Following example has a lot of improvements over yours.
static void Main(string[] args)
{
demo obj = new demo();
string uname, pass;
Console.ForegroundColor = ConsoleColor.Green;
int maxTries;
int tries = maxTries = 5;
do
{
if (tries != maxTries)//second and more
{
Console.Clear();
Console.WriteLine("Invalid");
Console.Write("\n\t" + tries + " Tries left");
Console.WriteLine("\n\n\n\tTry again? (y/n)");
string input;
do
{
input = Console.ReadLine();
} while (input != "y" && input != "n");
if (input == "n")
{
return; // exit the program
}
}
Console.Clear();
Console.WriteLine("Enter username");
uname = Console.ReadLine();
Console.WriteLine("Enter Password");
pass = Console.ReadLine();
obj.setName(uname);
obj.setPass(pass);
tries--;
} while (obj.getName() != "niit" || obj.getPass() != "1234");
Console.WriteLine("Wellcome");
}
PS: Classes should start with a capital letter.
goto is a relict of old times, it will mess with your programm structure and make things more complicated than they are. The only propper use i know is for fallthrough in switches, which also is needed only in rare cases.
A madeup one would be:
string vehicleType = "car";
switch(vehicleType)
{
case "truck":
Console.WriteLine("two wheeles and");
goto case "car";
case "car":
Console.WriteLine("two wheeles and");
goto case "motor cycle";
case "motor cycle":
Console.WriteLine("two wheeles");
break;
case "boat":
Console.WriteLine("no wheeles");
break;
}

C# program keeps asking user input questions more than once

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);
}

Categories

Resources