I'm really new to programming and have to write a little programming which tests if a number is smaller or bigger than 500, 2000 and 5000. Now I wrote this but it always takes the first else statement even if the number is bigger than 5000 it says the number is smaller than 500. Anybody knows why? Appreciate every help I get. :)
Here's the code:
double rebe, fuenfh = 500.00, zweit = 2000.00, fuenft = 5000.00;
//zweiPro = 2.00, fuenfPro = 5.00, zehnPro = 10.00;
Console.WriteLine("How big is the number? Wie groß war Ihr Rechnungsbetrag? ");
rebe = Console.Read();
if (rebe >= fuenfh)
{
if (rebe >= zweit)
{
if (rebe >= fuenft)
{
Console.WriteLine("bigger or same as 5000");
Console.ReadLine();
Console.Read();
}
else
{
Console.WriteLine("bigger or same as 2000 but smaller than 5000 // Groesser gleich als 2000 aber kleiner als 5000");
Console.ReadLine();
Console.Read();
}
}
else
{
Console.WriteLine("bigger or same as 500 but smaller than 2000 // Groesser gleich 500 aber kleiner als 2000");
Console.ReadLine();
Console.Read();
}
}
else
{
Console.WriteLine("smaller than 500 // Leider gibt es keinen Rabatt. :(");
Console.ReadLine();
Console.Read();
}
change your input from rebe = Console.Read(); to rebe = Convert.ToDouble( Console.ReadLine());. I don't think you're pulling in the value that you expected.
This is how it could work, converting the input to double (as hinted by mnield) but also making the code more readible in general. Note how much shorter the code gets when you invert your conditionals.
Console.WriteLine("How big is the number?");
double amount = Convert.ToDouble(Console.Readline());
if (amount < 500.0)
{
Console.WriteLine("smaller than 500");
}
else if (amount < 2000.0)
{
Console.WriteLine("bigger or same as 500 but smaller than 2000");
}
else if (amount < 5000.0)
{
Console.WriteLine("bigger or same as 2000 but smaller than 5000");
}
else
{
Console.WriteLine("bigger or same as 5000");
}
Console.ReadLine();
double fuenfh = 500.00, zweit = 2000.00, fuenft = 5000.00;
//zweiPro = 2.00, fuenfPro = 5.00, zehnPro = 10.00;
do
{
Console.WriteLine("\nWie groß war Ihr Rechnungsbetrag? ");
var eingabe = double.TryParse(Console.ReadLine(), out var rebe);
if (eingabe)
{
if (rebe >= fuenft) { Console.Write($"Die eingabe ist größer oder gleich {fuenft}"); }
else if (rebe >= zweit) { Console.Write($"Die eingabe ist größer oder gleich {zweit} aber kleiner als {fuenfh}"); }
else if (rebe >= fuenfh) { Console.Write($"Die eingabe ist größer oder gleich {fuenfh} aber kleiner als {zweit}"); }
else { Console.Write($"Die eingabe ist kleiner als {fuenfh}"); }
}
else { Console.WriteLine("Bitte Zahl eingeben!"); }
} while (true);
This way you'll have whole funktion in the loop!
double.TryParse - converts your input to the double type
if (eingabe) - if numbers are entered it sends you in the if blocks with your variables
do {} while (true) - endless loop to test your function without clicking debug all the time
Related
I'm coding "Higher / Lower".
I commented where is the problem. Please don't spoiler the full solution of that game.
static void Main(string[] args)
{
Console.WriteLine("Higher ! Lower Game");
Console.WriteLine("\nSchwierigkeitsstufen:\nEasy: 1 - 100\nMedium: 100 - 1000\nHard: 1000 - 10000");
Console.WriteLine("\nWähle ein Level!");
string auswahl = Convert.ToString(Console.ReadLine());
Console.WriteLine("\nDu hast " + auswahl + " gewählt\nBist du sicher?\n'Ja' / 'Nein'");
string confirm = Convert.ToString(Console.ReadLine());
/// TEXT
/// PROZESS
if (confirm == "Ja")
{
if (auswahl == "Easy")
{
Console.WriteLine("\nGebe eine Zahl ein!");
int eingabe = Convert.ToInt32(Console.ReadLine());
Random rnd = new Random();
int rmd = rnd.Next(0, 99);
while (eingabe != rmd)
{
int eingabe2 = Convert.ToInt32(Console.ReadLine());
while (eingabe < rmd)
{
Console.WriteLine("Higher");
return; /// Here, it should go back to "eingabe2" to let the user guess again. if im trying: "return eingabe2;" there comes the error "CS0127".
}
while (eingabe > rmd)
{
Console.WriteLine("Lower");
return; /// Here, it should go back to "eingabe2" to let the user guess again. if im trying: "return eingabe2;" there comes the error "CS0127".
}
}
}
}
}
Do you make your code work the first thing is to remove the nested loop (use if instead of while. I may be wrong but you should not need it. Just reassign your value.
Somethings you want to dig:
int.TryParse vs Convert.ToInt32()
while vs do...while
Enum type for you level (Level.Easy, Level.Medium, Level.Hard) and for Ja/Nein (Answer.Yes, Answer.No)
Guard pattern (return early to avoid nesting logic)
Spoilers below:
static void Main(string[] args)
{
Console.WriteLine("Higher ! Lower Game");
Console.WriteLine("\nSchwierigkeitsstufen:\nEasy: 1 - 100\nMedium: 100 - 1000\nHard: 1000 - 10000");
Console.WriteLine("\nWähle ein Level!");
string auswahl = Convert.ToString(Console.ReadLine());
Console.WriteLine("\nDu hast " + auswahl + " gewählt\nBist du sicher?\n'Ja' / 'Nein'");
string confirm = Convert.ToString(Console.ReadLine());
/// TEXT
/// PROZESS
if (confirm == "Ja")
{
if (auswahl == "Easy")
{
Console.WriteLine("\nGebe eine Zahl ein!");
var rnd = new Random();
var rmd = rnd.Next(0, 99);
var eingabe = -1;
while (eingabe != rmd)
{
eingabe = Convert.ToInt32(Console.ReadLine());
if (eingabe < rmd)
{
Console.WriteLine("Higher");
/// Here, it should go back to "eingabe2" to let the user guess again. if im trying: "return eingabe2;" there comes the error "CS0127".
}
if (eingabe > rmd)
{
Console.WriteLine("Lower");
/// Here, it should go back to "eingabe2" to let the user guess again. if im trying: "return eingabe2;" there comes the error "CS0127".
}
}
}
}
}
so I am pretty new to C# and after learning some fundamentals I tried making a simple program to check for someone's eligibility using if statements.
The program asks for 3 things: Age, Height, and CollegeDegree
You have to be 18 to go to the next question and you have to be taller than 160cm to go to the CollegeDegree question.
Now the program works fine, however looking at it, I come to realize that there are a lot of nested if statements and the code is just messy and unreadable.
What would I need to do to make it cleaner? I tried just doing it as follows
if
else
if
else
However, that causes the issue that if the first condition is not met, so the age is < 18 it just runs the next if statement instead of making the user be ineligible.
Current Code:
static void Main(string[] args)
{
int ageInput;
int heightInput;
bool hasCollegeDegree;
Console.WriteLine("How old are you?");
ageInput = Convert.ToInt32(Console.ReadLine());
if (ageInput >= 18)
{
Console.WriteLine("You are older than 18");
Console.WriteLine("How tall are you?");
heightInput = Convert.ToInt32(Console.ReadLine());
if (heightInput >= 160)
{
Console.WriteLine("You are taller than 160cm");
Console.WriteLine("Do you have a college degree?");
hasCollegeDegree = Convert.ToBoolean(Console.ReadLine());
if (hasCollegeDegree == true)
{
Console.WriteLine("You have a college degree");
Console.WriteLine("You are eligible");
}
else
{
Console.WriteLine("No College Degree");
Console.WriteLine("You are ineligible");
}
}
else
{
Console.WriteLine("You are too short");
}
}
else
{
Console.WriteLine("You are too young");
}
}
You can exit out of the code using a reverse condition. Example:
Console.WriteLine("How old are you?");
int ageInput = Convert.ToInt32(Console.ReadLine());
if (ageInput < 18)
{
Console.WriteLine("You are too young");
return;
}
Console.WriteLine("You are older than 18");
Console.WriteLine("How tall are you?");
int heightInput = Convert.ToInt32(Console.ReadLine());
if (heightInput < 160)
{
Console.WriteLine("You are too short");
return;
}
Console.WriteLine("You are taller than 160cm");
Console.WriteLine("Do you have a college degree?");
bool hasCollegeDegree = Convert.ToBoolean(Console.ReadLine());
if (!hasCollegeDegree)
{
Console.WriteLine("No College Degree");
Console.WriteLine("You are ineligible");
return;
}
Console.WriteLine("You have a college degree");
Console.WriteLine("You are eligible");
I suggest extracting methods to read integer:
private static int ReadInteger(string question) {
while (true) {
if (!string.IsNullOrWhiteSpace(question))
Console.WriteLine(question);
if (int.TryParse(Console.ReadLine(), out int result))
return result;
Console.WriteLine("Sorry, not a valid integer; please, try again.");
}
}
and boolean:
private static HashSet<string> s_Yes =
new HashSet<string>(StringComparer.OrdinalIgnoreCase) {
"Y", "Yes", "T", "True", "OK"
};
private static HashSet<string> s_No =
new HashSet<string>(StringComparer.OrdinalIgnoreCase) {
"N", "No", "F", "False"
};
private static bool ReadBoolean(string question) {
while (true) {
if (!string.IsNullOrWhiteSpace(question))
Console.WriteLine(question);
string input = Console.ReadLine().Trim();
if (s_Yes.Contains(input))
return true;
if (s_No.Contains(input))
return false;
Console.WriteLine("Sorry, not a valid value; please, try again.");
}
}
then you can put
if (ReadInteger("How old are you?") < 18) {
Console.WriteLine("You are too young");
return;
}
Console.WriteLine("You are older than 18");
if (ReadInteger("How tall are you?") < 160) {
Console.WriteLine("You are too short");
return;
}
Console.WriteLine("You are taller than 160cm");
if (!ReadBoolean("Do you have a college degree (Y/N)?")) {
Console.WriteLine("No College Degree");
Console.WriteLine("You are ineligible");
return;
}
Console.WriteLine("You have a college degree");
Console.WriteLine("You are eligible");
A disadvantage with the answers so far using return is that the method is exited and therefore you can't have any code below that point in the same method.
A different approach is to use a COMPOUND boolean statement and combine all the conditions into one boolean expression:
if (ageInput >= 18 && heightInput >= 160 && hasCollegeDegree)
{
Console.WriteLine("Congratulations! You meet the criteria.");
}
else
{
Console.WriteLine("You do not meet the criteria.");
}
This style of check might be useful if you have many different combinations that you need to check for. So the user enters all the information up front and then you can have a whole series of different compound checks to see which combinations they satisfy. Maybe you're checking to see which grants from a list that the user qualifies for.
See Boolean logical operators for more information on &&, ||, and !.
I would like for someone to help me by telling me what code I should use in case the input number turns out to be for the second if or third if, if the user doesn't put the right amount (73-77) then id like the user to be able to type in a new value I can use... how do I do that please?
namespace test
{
class Program
{
public static int FahrToCels(int fahr)
{
int cel = (fahr - 32) * 5 / 9;
return cel;
}
static void Main(string[] args)
{
Console.WriteLine("write down temprature: ");
int fahrenheit = int.Parse(Console.ReadLine());
int celsius = FahrToCels(fahrenheit);
Console.Write("Press any key to continue . . .");
Console.ReadKey(true);
do
if (celsius >= 73 && celsius <= 77)
{
Console.WriteLine("now it works ");
}
else if (celsius < 72)
{
Console.WriteLine("");
}
else if (celsius > 77)
{
Console.WriteLine("");
}
while (true);
}
}
}
There are a few major issues with what you have. Attached is working code for what I believe you are looking for, though in your ifs you have Celsius range in the 70s when the point of your Fahrenheit to Celsius converter turns the value into Celsius which would lie in the 20s range.
namespace test
{
class Program
{
public static int FahrToCels(int fahr)
{
int cel = (fahr - 32) * 5 / 9;
return cel;
}
static void Main(string[] args)
{
int celsius;
int fahrenheit;
do
{
Console.WriteLine("Skrive in Temperaturen: ");
fahrenheit = int.Parse(Console.ReadLine());
celsius = FahrToCels(fahrenheit);
Console.Write("Presifs any key to continue . . .");
Console.ReadKey(true);
if (celsius >= 22 && celsius <= 28)
{
Console.WriteLine("now it works ");
//Insert whatever here
break;
}
else if (celsius < 22)
{
//Something to tell them they need to retry
}
else if (celsius > 28)
{
//Something to tell them they need to retry
}
}
while (celsius >= 22 && celsius <= 28);
}
}
}
I would recommend changing the range on your ifs to the values you want the user to input, and also provide the user with some error/retry statement in your elseifs. Also would recommend instead of having two elseifs just use else. Also would remove that stupid readkey() in my opinion.
If you have any questions to my answer leave them in the comments.
If you want to ensure that celsius is in [73..77] range you can try
static void Main(string[] args) {
int fahrenheit;
int celsius;
// Keep asking user until (s)he enters a valid celsius value
while (true) {
Console.WriteLine("Skrive in Temperaturen: ");
// check if value a valid integer, and not say "bla-bla-bla"
if (!int.TryParse(Console.ReadLine(), out fahrenheit)) {
Console.WriteLine("Not an integer value, please, try again");
continue;
}
// fahrenheit is a valid integer value, we can compute corresponding celsius...
celsius = FahrToCels(fahrenheit);
// ... and validate the celsius value then
if (celsius < 73)
Console.WriteLine("Too low temperature (below 73 degree Celsius)");
else if (celsius > 77)
Console.WriteLine("Too high temperature (above 77 degree Celsius)");
else
break; // celsius is valid integer value in [73..77] range
}
// From now on celsius contains integer in [73..77] range
Console.WriteLine("Now it works");
Console.Write("Press any key to continue . . .");
Console.ReadKey(true);
}
I wrote this code for class a few days ago. Everything looks correct, however, when I enter the input, I immediately get an error.
Any help on this would be greatly appreciated.
Console.WriteLine("The following are the benefit packages: ");
Console.WriteLine("Employee only (E) ");
Console.WriteLine("Employee and spouse (S) ");
Console.WriteLine("Employee and children (C) ");
Console.WriteLine("Employee and family (F) ");
Console.WriteLine();
Console.WriteLine("Please select your benefit type for medical insurance: ");
string medical = Console.ReadLine();
double subtotal = Convert.ToDouble(Console.ReadLine());
///the error is with the double above. I'm not sure how to work around this.
if (medical == "e")
{
subtotal += 0;
}else if (medical == "s")
{
subtotal += 50;
}else if (medical == "c")
{
subtotal += 100;
}else if (medical == "f")
{
subtotal += 200;
}
Console.WriteLine("Please select your benefit type for dental insurance: ");
string dental = Console.ReadLine();
if (dental == "e")
{
subtotal += 50;
}else if (dental == "s")
{
subtotal += 125;
}else if (dental == "c")
{
subtotal += 225;
}else if (dental == "f")
{
subtotal += 325;
}
Console.WriteLine("Please select your benefit type for vision insurance: ");
string vision = Console.ReadLine();
if (vision == "e")
{
subtotal += 25;
}else if (vision == "s")
{
subtotal += 60;
}else if (vision == "c")
{
subtotal += 110;
}else if (vision == "f")
{
subtotal += 185;
}
Console.WriteLine("Please enter your years in service: ");
int years = Convert.ToInt16(Console.ReadLine());
double discount = Convert.ToDouble(Console.ReadLine());
if (years >= 20)
{
discount = .2;
}else if (years >= 10 && years < 20)
{
discount = .1;
}else if (years < 10)
{
discount = 0;
}
double total = subtotal + (subtotal * discount);
Console.WriteLine("Your total out-of-pocket premium: " + total);
Console.ReadLine();
Each time the user "selects" a package, the value of the "subtotal" will increase. Later, the final total is calculated for, giving the user a final cost of these premiums.
string medical = Console.ReadLine();
double subtotal = Convert.ToDouble(Console.ReadLine());
this is asking for two inputs, the first Console.ReadLine(); sets your string medical. this is good.
lets say i enter E
now medical = "E"
now before it gets to your loop to determine what to do with "E", your asking for another input, and trying to convert it to a double. i would change the second line:
double subtotal = Convert.ToDouble(Console.ReadLine());
to
double subtotal = 0.0;
this will give you an starting value. if you know the "procedure cost" which i assume is your double, you can set it to whatever you want, but if you want to ask for the value use:
double subtotal = double.Parse(System.Console.ReadLine());
also the way your options are set up....
Console.WriteLine("Employee only (E) ");
Console.WriteLine("Employee and spouse (S) ");
Console.WriteLine("Employee and children (C) ");
Console.WriteLine("Employee and family (F) ");
is going to encourage people to enter capital letters. this is fine, but you're only checking for lower case, i suggest:
if (vision == "e"||vision == "E")
EDIT: i forgot to tell you, when working with dollar amounts, its best to use decimal not double.
This is part of my code and I'm trying to make console.write to show new statement of "Please re-enter number greater than 20 : " only.
The problem is when I run my code it show "Please re-enter number greater than 20 : " as well as previous statement ("Enter amount of fuel used in litres : "). in one line.
How can I make it not to show first write statement ??
static double InputFuel()
{
double fFuel;
string text;
bool badValue = true;
do
{
Console.Write("Enter amount of fuel used in litres : ");
text = Console.ReadLine();
if (double.TryParse(text, out fFuel) && fFuel >= 20)
{
badValue = false;
}
else
{
Console.WriteLine("\n\t {0} is below the minimum value of 20 \n\n", text);
Console.Write("Please re-enter number greater than 20 : ");
}
} while (badValue);
return fFuel;
}//end InputTemp
Move the line Console.Write("Enter amount of fuel used in litres : "); outside the while-loop. In your example it is inside the while loop, so it is repeated every time an incorrect answer is entered. If you move it in front of the loop, it will only be written once to the console.
...
bool badValue = true;
Console.Write("Enter amount of fuel used in litres : ");
do
{
text = Console.ReadLine();
...
You can use Console.Clear() to clear the current contents of the Console. https://msdn.microsoft.com/en-us/library/system.console.clear(v=vs.110).aspx
For instance
static double InputFuel()
{
double fFuel;
string text;
bool badValue = true;
do
{
Console.Write("Enter amount of fuel used in litres : ");
text = Console.ReadLine();
if (double.TryParse(text, out fFuel) && fFuel >= 20)
{
badValue = false;
}
else
{
Console.Clear();
Console.WriteLine("\n\t {0} is below the minimum value of 20 \n\n", text);
Console.Write("Please re-enter number greater than 20 : ");
}
} while (badValue);
return fFuel;
}
static double InputFuel()
{
double fFuel;
string text;
bool badValue = true;
bool notFirst = false;
do
{
if(!notFirst)
Console.Write("Enter amount of fuel used in litres : ");
notFirst = true;
text = Console.ReadLine();
if (double.TryParse(text, out fFuel) && fFuel >= 20)
{
badValue = false;
}
else
{
Console.WriteLine("\n\t {0} is below the minimum value of 20 \n\n", text);
Console.Write("Please re-enter number greater than 20 : ");
}
} while (badValue);
return fFuel;
}
If I understood correctly, your problem is only an algorithmic problem :
static double InputFuel()
{
double fFuel;
string text;
bool badValue = true;
Console.Write("Enter amount of fuel used in litres : ");
do
{
text = Console.ReadLine();
if (double.TryParse(text, out fFuel) && fFuel >= 20)
{
badValue = false;
}
else
{
Console.Clear();
Console.WriteLine("\n\t {0} is below the minimum value of 20 \n\n", text);
Console.Write("Please re-enter number greater than 20 : ");
}
} while (badValue);
return fFuel;
}//end InputTemp
By putting out the first write out of the loop, it only shows the first time and then does not come again. If you want it to completely disappear, just add a Console.Clear(); in the else statement to erase what was displayed before, and it's done.
I suggest changing the loop into infinite one; if question should be stated just once pull it out of the loop:
Console.Write("Enter amount of fuel used in litres : ");
while (true) {
text = Console.ReadLine();
if (!double.TryParse(text, out fFuel))
Console.Write("Please re-enter number in correct format: ");
else if (fFuel <= 0)
Console.Write("Please re-enter number greater than 0 : ");
else if (fFuel >= 20)
Console.Write("Please re-enter number less than 20 : ");
else
break;
}