C# while loop not functioning [closed] - c#

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 4 years ago.
Improve this question
I am trying to build a stimulate income tax calculator. The progress I am wanting to make is :
print out a message of "What is your total income :" to ask user to input their income in positive numeric number.
to read their inputs
make a loop: if the user put in strings, print "Enter your income as a whole-dollar numeric number",and go back to step 1. If the user put in negative number, print "Your income cannot be negative",and go back to step 1.
4.if the user has successfully enter the positve numeric number, process to step 5.
print out a message "How many children do you have?"
read the user's input.
make a loop: if the user types in strings, print "You must enter a valid number", and go back to step 5. If the user types in negative number, print "You must enter a positive number", and go back to step 5.
if the user successfully enter the postive numeric number, process to step 9.
put the income and children's figure in the tax calculation formula. if the totalTax <= 0, print "You owe no tax". if the total Tax > 0, print "you have to pay [tax amount] tax". END
I have tried to use the code bellow, but it doesn't work at all.
//Record user's income into double list "income"
double i;
//Record user's number of children into double list "kid"
double k;
//if...elif statement to calculate the toatal tax of the user
bool incomeOK = false;
bool kidOK = false;
do
{
Console.Write("What is your total income : ");
incomeOK = double.TryParse(Console.ReadLine(), out i);
if (!incomeOK || i < 0)
{
if (!incomeOK)
{
Console.WriteLine("Enter your income as a whole-dollar numeric figure.");
}
else if (i < 0)
{
Console.WriteLine("Your income cannot be negative.");
}
}
else
{
Console.Write("How many children do you have: ");
kidOK = double.TryParse(Console.ReadLine(), out k);
while (!kidOK || k < 0)
{
Console.Write("How many children do you have: ");
kidOK = double.TryParse(Console.ReadLine(), out k);
if (kidOK && k >= 0)
{
//Calculate the total payable tax of the user
double totalTax = (i - 10000 - (k * 2000)) * 0.02;
if (totalTax <= 10000)
{
Console.WriteLine("You owe no tax.");
Console.WriteLine("\n\n Hit Enter to exit.");
Console.ReadLine();
}
else
{
Console.WriteLine("You owe a total of $ " + totalTax + " tax.");
Console.WriteLine("\n\n Hit Enter to exit.");
Console.ReadLine();
}
}
if (!kidOK || k < 0)
{
if (!kidOK)
{
Console.WriteLine("You must enter a valid number.");
}
else if (k < 0)
{
Console.WriteLine("You must enter a positive number.");
}
}
}
}
}
while (!incomeOK || !kidOK);
but the OUTPUT:
What is your total income : sfd
Enter your income as a whole-dollar numeric figure.
Press any key to continue...

You need to split it up into sections.
First: Get positive number
double i;
double k;
Console.Write("What is your total income : ");
while (!double.TryParse(Console.ReadLine(), out i) || i < 0)
{
if (i < 0)
{
Console.WriteLine("Your income cannot be negative.");
}
else
{
Console.WriteLine("Enter your income as a whole-dollar numeric figure.");
}
}
Second: Get number of children
Console.Write("How many children do you have: ");
while (!double.TryParse(Console.ReadLine(), out k) || k < 0)
{
if (k < 0)
{
Console.WriteLine("You must enter a positive number.");
}
else
{
Console.WriteLine("You must enter a valid number.");
}
}
Third: Calculate
double totalTax = (i - 10000 - (k * 2000)) * 0.02;
if (totalTax <= 10000)
{
Console.WriteLine("You owe no tax.");
Console.WriteLine("\n\n Hit Enter to exit.");
Console.ReadLine();
}
else
{
Console.WriteLine("You owe a total of $ " + totalTax + " tax.");
Console.WriteLine("\n\n Hit Enter to exit.");
Console.ReadLine();
}
Whenever you get a wrong input, the while loop forces you to stay inside. When you get out, you can be sure the input is correct.
PS: I would use int for number of children, because it doesn't make any sense that you would have 2.3 children.

In your code, you aren't looping when it successfully parses but is a negative number.
Since your two loops are basically independent of each other, I wouldn't wrap them together in a loop (unless you intend on asking multiple times, but then that's simply another loop to repeat outside). Keep it simple and its easier to see the error. I changed it to this:
do
{
Console.Write("What is your total income : ");
incomeOK = double.TryParse(Console.ReadLine(), out i);
if (!incomeOK)
{
Console.WriteLine("Enter your income as a whole-dollar numeric figure.");
continue;
}
if (i < 0)
{
Console.WriteLine("Your income cannot be negative.");
incomeOK = false; // You need to manually set this to false to indicate it is not ok for it to loop.
}
} while (!incomeOk)
do
{
Console.Write("How many children do you have: ");
kidOK = double.TryParse(Console.ReadLine(), out k);
if (!kidOK)
{
Console.WriteLine("You must enter a valid number.");
continue;
}
if(k < 0)
{
Console.WriteLine("You must enter a positive number.");
kidOK = false; // Same deal as before
continue;
}
/// ... Your calculations
} while (!kidOK);
The code is now in two loops, your inputs for income, and inputs for children. Also, there's really no need to check if it's (!incomeOK || i < 0) first. If it's not ok, you output your message and loop. If it's negative, output your message, and make sure it loops. Otherwise just proceed with normal.

Related

I am new here as well as into coding ! I solved a problem but i was wondering if the same problem could be solved in different/shorter ways?

The Problem:
Imagine you are a developer and get a job in which you need to create a program for a teacher. He needs a program written in c# that calculates the average score of his students. So he wants to be able to enter each score individually and then get the final average score once he enters -1.
So the tool should check if the entry is a number and should add that to the sum. Finally once he is done entering scores, the program should write onto the console what the average score is.
The numbers entered should only be between 0 and 20. Make sure the program doesn't crash if the teacher enters an incorrect value.
Test your program thoroughly.
My solution to the problem :
static void Main(string[] args)
{
int digit = 0,sum=0,counter=0;
string x;
try
{
for (int i = 0; i <= counter; i++)
{
Console.WriteLine("Please Enter Score");
x = Console.ReadLine();
bool isParsable = Int32.TryParse(x,out digit);
if (isParsable)
{
if (digit >= 0 && digit <= 20)
{
Console.WriteLine("Valid Number");
sum += digit;
counter++;
Console.WriteLine($"Student number {counter} got {digit}");
}
else if (digit == -1)
{
Console.WriteLine($"Total sum is {sum}");
Console.WriteLine($"Total number of students is {counter}");
Console.WriteLine($"Average score of {counter} students is {sum / counter}");
break;
}
else
{
Console.WriteLine("Please enter a valid score");
}
}
Console.WriteLine("Please enter Numerical Values only");
}
}
catch (DivideByZeroException)
{
Console.WriteLine("Unable to get results");
}
}

How can I find the minimum and maximum value within a decimal list?

I have created a list type decimal. I'm creating a method that does a couple simple analytics tasks. How do I find and display the minimum and maximum value within the list.
I haven't tried anything because I can't find the syntax.
static void Analytics()
{
Console.WriteLine("1 Display student grade average");
Console.WriteLine("2 Display Lowest grade + Student Name");
Console.WriteLine("3 Display Highest grade +Student Name");
Console.Write("Option: ");
string choice = Console.ReadLine();
decimal average;
if (choice == "1")
{
Console.Clear();
decimal gradeSum = 0m;
Console.WriteLine("Grades Analytics");
for (int count = 0; count < firstName.Count; count++)
{
gradeSum += studentGrade[count];
}
average = (gradeSum / studentGrade.Count) * .01m;
Console.Write("Average Grade: ");
Console.WriteLine(average.ToString("p2"));
}
else if (choice == "2")
{
Console.Clear();
//display min here
}
else if (choice == "3")
{
Console.Clear();
//display max here
}
}
You'll see the place I'm trying to write the code on choice # 2 & 3
Try using System.linq. With LINQ, you can have an expression like: studentGrade.Min(x => x.grade) to get the minimum grade, and studentGrade.Max(x => x.grade) to get the maximum. Give that a try.
I highly recommend looking more into LINQ as a C# developer. It is in my opinion, one of the best tools available to C# developers.

Code is supposed to include all of user's input but stops after third input

My code first takes the "s" or "k" or "c" input from the user to display a price. The user enters a coin value to bring down that price. My code works when the user inputs the "s" and the first coin value, but after that it just closes after a fourth input and I'm not sure why.
I tried ReadKey and Console.ReadLine but im not sure where to go from here
namespace VendingMachine
{
class Program
{
static void Main(string[] args)
{
//Gives user necessary info to operate vending machine
Console.WriteLine("Welcome to vending machine.");
Console.WriteLine("We offer you (s)oda, coo(k)ies, and (c)hips");
Console.WriteLine("Please select the product you want to purchase:");
string userselection = Console.ReadLine();
if (userselection == "s")
{
//Generates a random number between 0 and 5 using the random class
Random rn = new Random();
int randomnumber = rn.Next(1, 5);
double lottery = randomnumber * 10;
Console.WriteLine("Congratulations! You win a coupon with " + lottery + " cents.");
//soda price after lottery
double sodaprice = 100 - lottery;
Console.WriteLine("You only need to pay " + sodaprice + " cents");
Console.WriteLine("Please insert a coin of 5, 10, or 25:");
string coininput = Console.ReadLine();
double coin = Convert.ToDouble(coininput);
while (coin > 0)
{
if (coin == 25)
{
double sodapricecoins = sodaprice - coin;
Console.WriteLine("You still owe " + sodapricecoins + " cents.");
Console.WriteLine("Please insert a coin of 5, 10, or 25:");
break;
}
else if (coin == 10)
{
double sodapricecoins = sodaprice - coin;
Console.WriteLine("You still owe " + sodapricecoins + " cents.");
Console.WriteLine("Please insert a coin of 5, 10, or 25:");
break;
}
else if (coin == 5)
{
double sodapricecoins = sodaprice - coin;
Console.WriteLine("You still owe " + sodapricecoins + " cents.");
Console.WriteLine("Please insert a coin of 5, 10, or 25:");
break;
}
}
}
}
}
}
The program should be running continuously until it hits 0 or negative, I know I don't have that part yet.
The first thing to do is to remove the break inside the three if, but if you notice the three if contains the same code. They are not needed at all.
The second point is to have a way to exit the loop. This could be when the user types zero for the coin of if the amount due is equal or below zero.
The third point is to ask the coin value inside the loop, do the math and then decide if you want to continue the loop or stop it.
Console.WriteLine("You only need to pay " + sodaprice + " cents");
// To force to start the loop, we ask the value inside the loop
double coin = 1d;
// We should reach zero or less starting from the initial price (minus lottery)
double amountDue = sodaprice;
while (coin > 0)
{
Console.WriteLine("Please insert a coin of 5, 10, or 25:");
string coininput = Console.ReadLine();
// use tryparse when trying to convert user input in numbers.
// tryparse returns true if the input is a number without raising exceptions
if(double.TryParse(coininput, out coin))
{
// Decrement the amount to pay with the user input
amountDue -= coin;
// Decide for a message and continue the loop or stop
if(amountDue > 0)
Console.WriteLine("You still owe " + amountDue + " cents.");
else
break;
}
}
If you want that program runs continuously until sodaprice hits 0 or negative try this code, but your while loop with coin > 0 condition, continue until user types zero or negetive number.
//Gives user necessary info to operate vending machine
Console.WriteLine("Welcome to vending machine.");
Console.WriteLine("We offer you (s)oda, coo(k)ies, and (c)hips");
Console.WriteLine("Please select the product you want to purchase:");
string userselection = Console.ReadLine();
if (userselection == "s")
{
//Generates a random number between 0 and 5 using the random class
double lottery = new Random().Next(1, 5) * 10;
Console.WriteLine("Congratulations! You win a coupon with " + lottery + " cents.");
//soda price after lottery
double sodaprice = 100 - lottery;
Console.WriteLine("You only need to pay " + sodaprice + " cents");
double coin;
do
{
Console.WriteLine("Please insert a coin of 5, 10, or 25:");
if (double.TryParse(Console.ReadLine(), out coin))
{
if (coin == 25 || coin == 10 || coin == 5)
{
sodaprice -= coin;
Console.WriteLine(sodaprice > 0 ? "You still owe " + sodaprice + " cents." : "Finish...");
}
}
} while (sodaprice > 0);
}
Console.ReadLine();

Guessing Game Number Issue

Before I get down-voted for the extensive code, I feel it's necessary for a solution to present itself.
I've made alterations to the program's code from the help previously presented, but I still seem to be falling into the problem that the random number number is either not being properly compared (I've had examples where number is '5' and the user's guess is '5', but I'm still getting a comment that "You're quite far off! Try again." meaning it's falling into else if (userinputcalc > 4 | userinputcalc < 10)...
So, at this stage the issue seems to lie within the comparison of number and the userinput, leading to confusing output messages.
I'm probably missing something obvious here, despite being sure it's around the loop of comparing number and userinput but I've been looking at this code and seeing nothing.
Any help is greatly appreciated, as always.
public void GuessingGame()
{
string username; // Will be the user's chosen name for program interaction
int guessesleft = 0;// Stands for the number of guesses left (out of 3)
int spaceaway = 0; // Space from the guess and the random number, if not correct guess
int roundcount = 1; //Started at 1 for the sake of the user interface - aesthetics
int number = 0; // Current value of the random number
int userinput = 0; //User input is the guess the user makes during the guessing game
int userinputcalc = 0;// calculation of guess and random number, when added to spaceaway calculation
int answersright = 0; // Number of times the user guessed the number correctly
Random rndm = new Random(); // Initialises a new class of random, which'll be used to simulate the random number
Console.WriteLine("Welcome to Guessing Game!");
Console.WriteLine("");
Console.WriteLine("Please press any button to continue.");
Console.ReadLine();
Console.WriteLine("What's your name?");
username = (Console.ReadLine());
//If you're wondering at all, the "You must guess what it is inthree tries." is intentional, since it was showing double-spaced in the command prompt
Console.WriteLine("Well, " + username + ", I am thinking of a number from 1 to 10. You must guess what it is inthree tries.");
Console.WriteLine("");
{
do
{
Console.WriteLine("Round" + roundcount); //Displays the which round (out of 10) to the user
guessesleft = 3; //The remaining guesses left for the user
do
{
number = rndm.Next(10) + 1; // int number is set to a random number between 1 and 10
Console.WriteLine("Please enter a guess:");
userinput = int.Parse(Console.ReadLine());
guessesleft = guessesleft - 1;
if (userinput == number)
{
//Below, once you've guessed right, you will have this message displayed in the console
Console.WriteLine("You guessed " + number + " *RIGHT*!");
answersright = answersright + 1;
guessesleft = 0;// No point need to guess further on something you've guessed correctly - saves correct answer value exploit
}
else if (userinput < 1 || userinput > 10) // If user's guess is less than 1 or more than 10, then out of range. Counts as a guess.
{
Console.WriteLine("You guessed " + userinput + "! and it was incorrect!");
Console.WriteLine("This is outside of the range of numbers between 1-10 ");
}
else if (userinput != number) // while the user's guess does not equal the number
{
{
// userinputcalc = Math.Abs(number - userinput);
//Left out as I was getting abnormal run-time outputs and the math showed up wrong.
//(Example: RND No. = 5 Userinput = 5 Output: "Incorrect" "Hot")
spaceaway = (number - userinput); // Works out how far from the random no. the user's guess is.
// If user guesses 6 and random no. is 5, answer will be -1 this makes the value +ve and allows output to be shown without error
if (spaceaway < 0)
{
spaceaway = (spaceaway * -1);
userinputcalc = spaceaway;
}
else if (spaceaway > 0)
{
userinputcalc = spaceaway;
}
}
{
if (userinputcalc < 2)
{
Console.WriteLine("You guessed " + userinput + "! and it was wrong!");
Console.WriteLine("Hot");
}
else if
(userinputcalc < 3)
{
Console.WriteLine("You guessed " + userinput + "! and it was wrong!");
Console.WriteLine("Warm");
}
else if
(userinputcalc < 4)
{
Console.WriteLine("You guessed " + userinput + "! and it was wrong!");
Console.WriteLine("Cold");
}
else if (userinputcalc > 4 | userinputcalc < 10)
{
Console.WriteLine("You guessed " + userinput + "! and it was wrong!");
Console.WriteLine("You're quite far off! Try again.");
}
}
}
} while (guessesleft > 0);
Console.WriteLine("");
Console.WriteLine("The number was, "+number+"!");
Console.WriteLine("");
roundcount = roundcount + 1;
} while (roundcount < 11);
Console.WriteLine("Well, " + username + ". " + "You guessed correctly, " + answersright + " times!");
}
}
}
}
OK I think theres quite a few issues here (some are off topic but definitely worth mentioning)..
I wouldn't advise using while loops to check for specific inputs
For example:
Instead of roundCount != 11 use roundCount < 11
Then there is less chance of forever getting stuck in a loop
You should declare Random outside of your loops otherwise you run the risk of just getting the same numbers ("randomly")
You reset the number to a new number after every guess so the user doesn't have a chance to guess the right number
With all this being said, I think the Math.Abs was correct if you are trying to find the distance away from the number.. I wouldnt use less than two though as that would mean only numbers that are 1 away from the answer are "hot"
Note: Answer is based off question revision #5
Update
Doesn't seem like you were far off but you still reset the number every loop
number = rndm.Next(10) + 1; //Insert here
do
{
//Displays the which round (out of 10) to the user
Console.WriteLine("Round" + roundcount);
guessesleft = 3; //The remaining guesses left for the user
do
{
// Remove this -- number = rndm.Next(10) + 1;
I think this is what you want,please try it:
static int guessesleft;
static Random ran = new Random();
static int MagicNumber;
static string UserInput;
static void Main(string[] args)
{
ConsoleKeyInfo ci = new ConsoleKeyInfo();
do
{
guessesleft = 3;
UserInput = "";
Console.Clear();
string username;
int guesscount = 1;
Console.WriteLine("Welcome to Jackie's Guessing Game!");
Console.WriteLine("");
Console.WriteLine("Please press any button to continue.");
Console.ReadLine();
Console.WriteLine("What's your name?");
username = (Console.ReadLine());
//If you're wondering at all, the "You must guess what it is inthree tries." is intentional, since it was showing double-spaced in the command prompt
Console.WriteLine("Well, " + username + ", I am thinking of a number from 1 to 10. You must guess what it is inthree tries.");
Console.WriteLine("");
MagicNumber = ran.Next(1, 11);
do
{
Console.WriteLine("Please insert your " + guesscount++ + "º guess!");
UserInput = Console.ReadLine().Trim();
if (UserInput == MagicNumber.ToString())
break;
if (Math.Abs(Convert.ToInt32(UserInput) - MagicNumber) < 2)
Console.WriteLine("Hot!!");
else if(Math.Abs(Convert.ToInt32(UserInput) - MagicNumber) < 3)
Console.WriteLine("Warm!!");
Console.WriteLine("No luck , you have " + --guessesleft + "º guesses left!");
Console.WriteLine();
} while (guesscount < 4);
if (guesscount == 4)
Console.WriteLine("Sorry " + username + " no more tries,you lost!");
else
Console.WriteLine("Congratulations your guess with number " + UserInput + " is correct,the number was " + MagicNumber);
Console.WriteLine("Press Q to quit or Enter to Play again!");
ci = Console.ReadKey();
} while (ci.Key != ConsoleKey.Q);
}

Please help i have got very confused with the if statement below

I want the user to input a number, but if it is below zero I would like to show an error message and then loop round and ask the user for another number. Here is the code I have at the moment.
// this determines what the loop does.
for (int CustPos = 0; CustPos < LineNum; CustPos = CustPos + 1)
{
// this asks the user to enter the sales figures
Console.Write("enter sales figures for" + customer[CustPos] + " ");
// this is user's input is read in and stored.
sales_figures[CustPos] = Double.Parse(Console.ReadLine());
if (sales_figures[CustPos] < MIN_SALES_FIGURE) //True - continue
{
Console.WriteLine("");
Console.WriteLine("entry invalid");
Console.WriteLine("enter another value");
}
else//FALSE -> Go back to start of loop
{
Console.WriteLine("");
}
//this section displays the cust name, sales figure 70/30.
Console.WriteLine(" ");
fee_payable[CustPos] = (sales_figures[CustPos] / 100.0)
* licence_fee_in_percent[CustPos];
Console.WriteLine(customer[CustPos] +
" ----------- " + fee_payable[CustPos]);
Console.WriteLine("Licence fee to be paid in GBP is :" +
fee_payable[CustPos]);
seventy_percent_value = ((fee_payable[CustPos] / 10.0) * 7);
Console.WriteLine("70 percent of this fee is" +
seventy_percent_value);
thirty_percent_value = ((fee_payable[CustPos] / 10.0) * 3);
Console.WriteLine("30 percent of this fee is" +
thirty_percent_value);
Console.WriteLine(" ");
}
. Please help all advice will be greatly appreciated!
Thanks
I think a do-while loop would be better here, pseudocode:
userInput = -1
do
{
userInput = Console.ReadLine
}
while (userInput <0)
Colin E.
Youre on the right track, just look at the keyword Continue
This is the example in the link:
using System;
class ContinueTest
{
static void Main()
{
for (int i = 1; i <= 10; i++)
{
if (i < 9)
{
continue;
}
Console.WriteLine(i);
}
}
}
Note: The continue statement passes control to the next iteration of the enclosing iteration statement in which it appears.
if (sales_figures[CustPos] < MIN_SALES_FIGURE) //True - Continue //FALSE -> Go back to start of loop
You don't actually have any code here to make it go back to the start of the loop.
I recommend that you write it all out as pseudocode first, then turn it into code:
if (number entered is too low)
then restart loop
otherwise carry on
Instead of an if, you'll want a while:
while( sales_figure[CustPos] < 0 )
{
Console.Write("enter sales figures for" + customer[CustPos] + " ");
sales_figures[CustPos] = Double.Parse(Console.ReadLine());
}
Which guarantees that it will keep prompting until they enter something greater than zero.
Continue, does NOT do what you want it to. Continue means, "move on and ignore this iteration" which means you'd have an incorrect value for that customer.
Use a WHILE loop in combination with your IF:
continueflag = 0;
while (continueflag == 0)
{
sales_figures[CustPos] = Double.Parse(Console.ReadLine());
Console.WriteLine("");
if (sales_figures[CustPos] >= MIN_SALES_FIGURE) {
Console.WriteLine("entry invalid");
Console.WriteLine("enter another value");
} else continueflag = 1;
}

Categories

Resources