Simple For loop and if statement - c#

What I am trying to do is limit the withdrawal amount by $20 increments up to $500. I know I am missing some simple element in here to do this. My code worked until I tried to do the increments of 20.
double AccountBalance = 1500;
double WithdrawalAmount;
WithdrawalAmount = double.Parse(textInput.Text);
Double MaxWithdrawalAmount = 0;
for (MaxWithdrawalAmount = 0; MaxWithdrawalAmount <= 500; MaxWithdrawalAmount += 20)
{
if (WithdrawalAmount == MaxWithdrawalAmount)
{
double Total = (AccountBalance - WithdrawalAmount);
textTotal.Text = ("Total amount" + Convert.ToString(Total));
}
else
{
textError.Text = ("Only Increments of $20 allowed for withdraw up to $100");
textTotal.Text = ("" + AccountBalance);
}
}

You should handle your loop in a different way
bool ok = false;
for (MaxWithdrawalAmount = 0; MaxWithdrawalAmount <= 500; MaxWithdrawalAmount += 20)
{
if (WithdrawalAmount == MaxWithdrawalAmount)
{
double Total = (AccountBalance - WithdrawalAmount);
textTotal.Text = "Total amount" + Convert.ToString(Total);
ok = true;
break;
}
}
if (!ok)
{
textError.Text = ("Only Increments of $20 allowed for withdraw up to $100");
textTotal.Text = ("" + AccountBalance);
}
I have moved the error message outside the loop. If, inside the loop I find the correct value for withdrawal then I stop the loop and set a flag to avoid the final error message
Side note, if you don't need double values the whole code could be reduced to a few lines using the remainder operator . For example
int WithdrawalAmount = 120;
if ((WithdrawalAmount % 20) == 0)
... good ...
else
... bad ...

Related

Question about executing a while loop in C#

So I have this code where you enter your "area code" and then you enter how long you would like the call to be. This is basically a simple calculator that would find the cost of how much a call would be depending on your area code. I am having trouble trying to figure out how to keep the loop running if I enter in an invalid area code. As of now if I enter in an invalid area code the entire program will just end in the command prompt. Heres the code:
using System;
using static System.Console;
namespace Chapter6._1
{
class Program
{
static void Main()
{
// array info //
int[] phoneAreacode = { 608, 414, 262, 815, 715, 920 };
double[] phoneCost = { .05, .10, .07, .24, .16, .14 };
// declaring variables //
int x;
int areaCode;
double cost = 0;
int callLength;
bool validAreacode = false;
// start of actual code //
Write("Enter in the area code you want to call: ");
areaCode = Convert.ToInt32(ReadLine());
x = 0;
while (x < phoneAreacode.Length && areaCode != phoneAreacode[x])
++x;
if(x != phoneAreacode.Length)
{
validAreacode = true;
cost = phoneCost[x];
}
if (validAreacode)
{
Write("Enter in the length of your call: ");
callLength = Convert.ToInt32(ReadLine());
double finalCost = callLength * cost;
WriteLine("Your call to area code " + areaCode + " for " + callLength + " minutes will cost " + finalCost.ToString("C"));
}
else
{
WriteLine("YOU MUST ENTER A VALID AREA CODE!");
}
}
}
}
You might wrap your Read and Check routine into another while-loop:
bool validAreacode = false;
while(!validAreacode)
{
// start of actual code //
Write("Enter in the area code you want to call: ");
areaCode = Convert.ToInt32(ReadLine());
x = 0;
while (x < phoneAreacode.Length && areaCode != phoneAreacode[x])
++x;
if(x != phoneAreacode.Length)
{
validAreacode = true;
cost = phoneCost[x];
}
else
{
WriteLine("YOU MUST ENTER A VALID AREA CODE!");
}
}
This is the simplest solution for you (not so much changes in your code required). But your code still has the problems. Your program will be crashed if user tries to print any not digit character instead of area code.
You can do a do-While here:
Basically when you do do-while you force the code on the do to be done until the condition in the while is completed. in your case, you need to add the checking of the pohne number inside the do statement, and to know if the person selected a correct value, you can do Array.FindIndex():
this will be your do-while loop, also i chaned your x for index try to use names for the variables that have some meaning. (index is not perfect anyway)
do
{
Write("Enter in the area code you want to call: ");
areaCode = Convert.ToInt32(ReadLine());
index = Array.FindIndex(phoneAreacode, w => w == areaCode);
if (index >= 0)
{
validAreacode = true;
}
else
{
WriteLine("YOU MUST ENTER A VALID AREA CODE!");
}
} while (!validAreacode);
and this will be your entire main method:
int[] phoneAreacode = { 608, 414, 262, 815, 715, 920 };
double[] phoneCost = { .05, .10, .07, .24, .16, .14 };
// declaring variables //
int index;
int areaCode;
int callLength;
bool validAreacode = false;
// start of actual code //
do
{
Write("Enter in the area code you want to call: ");
areaCode = Convert.ToInt32(ReadLine());
index = Array.FindIndex(phoneAreacode, w => w == areaCode);
if (index >= 0)
{
validAreacode = true;
}
else
{
WriteLine("YOU MUST ENTER A VALID AREA CODE!");
}
} while (!validAreacode);
Write("Enter in the length of your call: ");
callLength = Convert.ToInt32(ReadLine());
double finalCost = callLength * phoneCost[index];
WriteLine("Your call to area code " + areaCode + " for " + callLength + " minutes will cost " + finalCost.ToString("C"));
As you can see you can also remove the while you have to loop the array and the if-else for the valid codes. assuming that when the code reach that point, the area is correct.
It's a good practice to try to remove the number of if-else.
You probably need to loop the entire code section, something like this
while (true)
{
Write("Enter in the area code you want to call: ");
var input = ReadLine();
if (input == "Exit")
break;
areaCode = Convert.ToInt32(input);
x = 0;
while (x < phoneAreacode.Length && areaCode != phoneAreacode[x])
++x;
if(x != phoneAreacode.Length)
{
validAreacode = true;
cost = phoneCost[x];
}
else if (validAreacode)
{
Write("Enter in the length of your call: ");
callLength = Convert.ToInt32(ReadLine());
double finalCost = callLength * cost;
WriteLine("Your call to area code " + areaCode + " for " + callLength + " minutes will cost " + finalCost.ToString("C"));
}
else
{
WriteLine("YOU MUST ENTER A VALID AREA CODE!");
}
}
Don't forget to add a check for when user types something that's not a digit

Keeping accurate conditions during loop repetition

I'm doing one method for calculating a pause, which has certain breaks checks. The method of calculating the time (from-to), at the same time I want to check, and if the time is less than 30, let me report the error.
It would have succeeded in a commencement if the loop would not have been repeated.
Can I somehow, if the condition is correct, skip that part?
In the pause of the variables I come to my values: 6, 56, 4
this is the method
private double CalculateBreak(List<PRAESENZZEIT> arrivals, out string error)
{
error = null;
double totalBreak = 0;
for (int i = 1; i < arrivals.Count();)
{
for (int n=i-1; n < arrivals.Count();)
{
double pause = (arrivals[i].ZPZ_Von - arrivals[n].ZPZ_Bis).TotalMinutes;
//this part
if (pause > 30)
error = "OK";
else
error = "error1";
//end
i += 1;
totalBreak += pause;
break;
}
if (totalBreak < 60)
{
error = "error2";
}
}
return totalBreak;
}
Edit: after some to-and-fro in the comments there is a further change required. If this still doesn't do what you want then lease open another question which concentrates on that part alone because I have no idea what you're saying. Code in the original answer commented out. This now returns the error if there has been one
Your loops are wrong. You only need one of them. The for n loop is going through all arrivals, when it looks like you only need to look at the previous one. Try something like this:
private double CalculateBreak(List<PRAESENZZEIT> arrivals, out string error)
{
error = null;
double totalBreak = 0;
for (int i = 1; i < arrivals.Count();)
{
// Check the i-th against the previous one (i - 1)
double pause = (arrivals[i].ZPZ_Von - arrivals[i - 1].ZPZ_Bis).TotalMinutes;
// //this part
// if (pause > 30)
// error = "OK";
// else
if (pause < 30) // new
{ // new
error = "Pausenzeitverletzung";
} // new
//end
i += 1;
totalBreak += pause;
// break;
// if (totalBreak < 60)
// {
// error = "Pausenzeitverletzung";
// }
}
// new: moved if block
if (totalBreak < 60)
{
error = "Pausenzeitverletzung";
}
return totalBreak;
}

Keeping track of points in simple console game

I'm having a hard time wrapping my mind around this. Every time the player makes a wrong guess, it should subtract his/her bet from the initial balance.
Since it is in a loop, it always takes the initial balance from the beginning spits out the same balance every time. (obviously)
I've tried assigning different variables and just can't seem to figure it out.
I've omitted the medium and hard difficulty methods as they are of no use right now, until I figure out this one.
My Main() only calls the setDifficulty(). Nothing else.
class Control
{
int selectedNumber = 0;
Random num = new Random();
bool playAgain = true;
int difficulty = 0;
int bet = 0;
int initialBalance = 20;
int runningCredits = 0;
int credits = 0;
public Control()
{ }
//sets game difficulty
public void SetDifficulty()
{
Console.Clear();
Console.WriteLine("Please select level of difficulty between 1 - 100");
difficulty = int.Parse(Console.ReadLine());
if (difficulty >= 1 && difficulty <= 20)
LetsPlayEasy();
else if (difficulty >= 21 && difficulty <= 50)
LetsPlayMedium();
else if (difficulty >= 51 && difficulty <= 100)
LetsPlayHard();
else
{
SetDifficulty();
}
}
//easy level method
public void LetsPlayEasy()
{
//variables
int userGuess;
int numGuesses = 0;
selectedNumber = num.Next(1, 101);
Console.BackgroundColor = ConsoleColor.DarkYellow;
Console.Clear();
Console.ForegroundColor = ConsoleColor.White;
Console.WriteLine("Difficulty level = EASY");
Console.WriteLine("\nBeggining credit balance = " + initialBalance);
Console.WriteLine("\nPlease place a bet. You will lose those credits for every incorrect guess!");
bet = int.Parse(Console.ReadLine());
do
{
Console.WriteLine("\nGuess a number between 1 and 100.");
userGuess = Convert.ToInt32(Console.ReadLine());
numGuesses++;
UI output = new UI();
output.CompareNumbers(userGuess, ref selectedNumber, ref playAgain, ref numGuesses);
runningCredits = (initialBalance - bet);
Console.WriteLine("\nYou have " + runningCredits + " credits remaining.");
} while (playAgain == true);
}
class UI
{
Random num = new Random();
int keepGoing;
public UI()
{ }
//compare user's guess to selected number
public void CompareNumbers(int userGuess, ref int selectedNumber, ref bool playAgain, ref int numGuesses)
{
Control difficulty = new Control();
Admin say = new Admin();
if (userGuess > selectedNumber)
{
Console.Beep(600, 300);
Console.WriteLine("\nToo High! Guess Again!");
}
else if (userGuess < selectedNumber)
{
Console.Beep(300, 300);
Console.WriteLine("\nToo Low! Guess Again!");
}
else
{
Console.Beep(350, 300);
Console.Beep(380, 200);
Console.Beep(380, 100);
Console.Beep(500, 1100);
Console.WriteLine("\n\nCongrats! It took you " + numGuesses + " guesses to win.");
numGuesses = 0;
Console.WriteLine("Press 1 to play again or 2 to quit.");
keepGoing = int.Parse(Console.ReadLine());
while (keepGoing != 1 && keepGoing != 2)
{
Console.WriteLine("\n\nPlease type either 1 or 2 only!");
keepGoing = int.Parse(Console.ReadLine());
}
if (keepGoing == 2)
{
playAgain = false;
say.Goodbye();
}
else
{
Console.Clear();
difficulty.SetDifficulty();
}
}
}
}
}
Initialise runningBalance to initialBalance and only use this value for calculations. If you only need initialBalance once, you can also do it by simply switching runningBalance to initialBalance without initializing runningBalance.
Console.WriteLine("\nBeggining credit balance = " + initialBalance);
Console.WriteLine("\nPlease place a bet. You will lose those credits for every incorrect guess!");
bet = int.Parse(Console.ReadLine());
runningBalance = initialBalance
do
{
Console.WriteLine("\nGuess a number between 1 and 100.");
userGuess = Convert.ToInt32(Console.ReadLine());
numGuesses++;
UI output = new UI();
output.CompareNumbers(userGuess, ref selectedNumber, ref playAgain, ref numGuesses);
runningCredits -= bet;
Console.WriteLine("\nYou have " + runningCredits + " credits remaining.");
} while (playAgain == true);
runningCredits = (initialBalance - bet);
You don't change initialBalance or bet in the loop, so every iteration has the same value of runningCredits.
Outside the loop, do this:
runningCredits = initialBalance;
Inside the loop, do this:
runningCredits -= bet;
Note: you don't have any code to check in the loop to see if the user guessed right or wrong (and as such, the user always loses and you always subtract out the bet).

Not receiving the correct Output in C#

So I am doing a homework assignment and for some reason my variable is not giving me the correct output. Using 6, 7, 8, 9, 10 as the judge scores and 1.2 as the degree of difficulty, I should receive 9.6 back for the final dive score.. but for some reason I am receiving 8.. Any ideas?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Rickerson_Bret_iLab3
{
class Program
{
static void Main(string[] args)
{
string wouldContinue;
do
{
string diverName;
string diverCity;
double degreeofDiff = 0;
double scoreJudge = 0;
bool validDegree = false;
double totalJudgeScore = 0;
int i = 1;
double highJudgeScore = 0;
double lowJudgeScore = 0;
Console.WriteLine("Enter the diver's name...");
diverName = Convert.ToString(Console.ReadLine());
Console.WriteLine("Enter the diver's city...");
diverCity = Convert.ToString(Console.ReadLine());
while (validDegree == false)
{
Console.WriteLine("Enter the degree of difficulty for this dive...");
degreeofDiff = Convert.ToDouble(Console.ReadLine());
if (degreeofDiff < 1.00 || degreeofDiff > 1.67)
{
Console.WriteLine("Re-enter a valid degree of difficulty (Valid Range: 1.00 - 1.67");
validDegree = false;
}
else
{
validDegree = true;
}
}
while (i < 6)
{
Console.WriteLine("Enter the judge #" + i + " score...");
scoreJudge = Convert.ToDouble(Console.ReadLine());
if (scoreJudge > 10 || scoreJudge < 1)
{
bool validScore = false;
while (validScore == false)
{
Console.WriteLine("Enter a valid Judge Score for judge #" + i + "...");
scoreJudge = Convert.ToDouble(Console.ReadLine());
if (scoreJudge > 10 || scoreJudge < 1)
{
validScore = false;
}
else
{
validScore = true;
}
}
}
if (scoreJudge > highJudgeScore)
{
highJudgeScore = scoreJudge;
Console.WriteLine(highJudgeScore);
}
if (scoreJudge < lowJudgeScore)
{
lowJudgeScore = scoreJudge;
Console.WriteLine(lowJudgeScore);
}
i++;
totalJudgeScore = totalJudgeScore + scoreJudge;
Console.WriteLine(totalJudgeScore);
Console.WriteLine(scoreJudge);
}
double highLow = highJudgeScore + lowJudgeScore;
totalJudgeScore = totalJudgeScore - highLow;
totalJudgeScore = (totalJudgeScore / 3) * degreeofDiff;
Console.WriteLine("Diver: " + diverName);
Console.WriteLine("Diver City: " + diverCity);
Console.WriteLine("Dive Degree of Difficulty: " + degreeofDiff);
Console.WriteLine("Dive Score: " + totalJudgeScore);
Console.WriteLine("Would you like to enter another diver? Enter y for yes or n for no...");
wouldContinue = Convert.ToString(Console.ReadLine());
wouldContinue.ToUpper();
} while (wouldContinue == "Y");
}
}
}
I want to add. I attempted to verify that it was accepting the data correctly by having it display the variables as it went through or anytime the variable was manipulated...it appears to be correct throughout but at the end is when I have the issue with variable "totalJudgeScore"
Edit2: I have since found that for some reason the code is not following the last 2 if statements properly. It is storing "scoreJudge" to "highJudgeScore" and "lowJudgeScore" each time and overwriting the data incorrectly.
Your lowJudgeScore is never getting set after it gets set to 0. You should have it default to 10 or higher, so that it gets set correctly.
Try this:
double lowJudgeScore = 10.0;
What happens is that the lowJudgeScore is never set during the loop. Add this else block and to initialize the lowJudgeScore...
if (scoreJudge < lowJudgeScore)
{
lowJudgeScore = scoreJudge;
Console.WriteLine(lowJudgeScore);
}
//Add this else block to initialize the low score variable
else if (lowJudgeScore == 0)
{
lowJudgeScore = scoreJudge;
}

How do I check if a number in a textbox is greater than a predefined value

im doing an exercise where i have to make a parking lot application.
The objectives are: Create a form with a numericUpDown control for choosingthe amount of time a vehicle was parked. Add option buttons to show if the vehicle is a car or truck. Clearly label each box and button. Add a label or text box to show the amount to pay.
Also, i have to set some limits. Cars shouldn't pay more than $38.00 for 24 hours, and trucks no more than $44.50 for 24 hours.
The only problem i find is that i cannot set these limits. It gives an error: Use of unassigned local variable 'result' .
Check the commented /// code.
Any help much appreciated. It's not a schoolwork project, i'm just learning c# by myself and doing some exercises.
Here's the code:
private void calculate_Click(object sender, EventArgs e)
{
double carhours = 3;
double truckhours = 3.50;
double carFirsthour = 5;
double truckFirsthour = 6;
int hrs = (int)numericUpDown.Value;
double result;
int maxCarFee = 38;
if (numericUpDown.Value < 1)
{
MessageBox.Show("NO WAY");
return;
}
if (carButton.Checked == true && (numericUpDown.Value == 1))
{
result = (hrs * carFirsthour);
fee.Text = "$" + result;
}
if (carButton.Checked == true && (numericUpDown.Value > 1))
{
result = ((hrs - 1) * carhours + carFirsthour);
fee.Text = "$" + result;
}
if (truckButton.Checked == true && (numericUpDown.Value == 1))
{
result = (hrs * truckFirsthour);
fee.Text = "$" + result;
}
if (truckButton.Checked == true && (numericUpDown.Value > 1))
{
result = ((hrs - 1) * truckhours + truckFirsthour);
fee.Text = "$" + result;
}
/// limits
///if (carButton.Checked == true && (numericUpDown.Value < 24) && (result > maxCarFee))
///{
/// fee.Text = "$" + maxCarFee;
///}
}
Try something like this:
private void calculate_Click(object sender, EventArgs e) {
double carhours = 3.0;
double truckhours = 3.5;
double carFirsthour = 5.0;
double truckFirsthour = 6.0;
double maxCarFee = 38.0;
double maxTruckFee = 44.5;
int hrs = (int)numericUpDown.Value;
double result;
if (hrs < 1) {
MessageBox.Show("NO WAY");
return;
}
if (carButton.Checked) {
result = (hrs-1) * carhours + carFirsthour;
if (result > maxCarFee) {
result = maxCarFee;
}
}
else {
result = (hrs-1) * truckhours + truckFirsthour;
if (result > maxTruckFee) {
result = maxTruckFee;
}
}
fee.Text = "$" + result;
}
However, you don't really make it clear what should happen if a car/truck stays for more than 24 hours (or more than 48 hours). You might end up with more consistent results with something like this:
private void calculate_Click(object sender, EventArgs e) {
double hourlyFee = 3.0;
double firstHourFee = 5.0;
double max24hrFee = 38.0;
if (!carButton.Checked) {
hourlyFee = 3.5;
firstHourFee = 6.0;
max24hrFee = 44.5;
}
int hrs = (int)numericUpDown.Value;
if (hrs < 1) {
MessageBox.Show("NO WAY");
return;
}
double result = 0.0;
if (hrs >= 24) {
result = (hrs / 24) * max24hrFee;
hrs = hrs % 24;
}
if (hrs > 0) {
result = result + firstHourFee + ((hrs-1) * hourlyFee);
}
fee.Text = "$" + result;
}
you need to convert numericUpDown.Value
to int32
or becuase you did this:
int hrs = (int)numericUpDown.Value;
you can just use hrs instead of numericUpDown.Value in the if statement
The problem is that none of the conditional (if) statements are executed so result is never assigned a value. Assign result in its declaration -- double result = 0D; -- and the code will run so you can debug the conditional logic.
You check if numericUpDown.Value is smaller than 24, i think you mean is greater (>)?!
Use of unassigned local variable 'result'
means you do not initialise the variable. you have to do something like this
result = 0
before you go to the if construct.
int hrs = (int)numericUpDown.Value;
You get value in hrs so you can use this in your if conditions.
if (carButton.Checked == true && (numericUpDown.Value == 1))
Write it like following. No need of == true
if (carButton.Checked && (numericUpDown.Value == 1))

Categories