My program collects the number of bottles collected by four rooms. When the user types in quit at anytime, the program goes out of the while look and shows the outcome of the bottle collection. It then calculates the winning room with the most bottle count.
I have a while loop I dont understand why I cant enter it. To enter the while loop, it will prompt me to enter a number 1-4, as used in my array, and the number of bottles each of the room has collected. If i type quit at anytime, the program will stop recording bottles and spit out the outcome and the winning room with the most bottles.
How do I get "Enter the room number you are in" to show up first before I enter in the bottle count? My problem exists in getBottles()
I think this line cant be used in an array, am i right?
rooms[room - 1] += int.Parse(Console.ReadLine());
namespace BottleDrive
{
class BottleDrive
{
public int[] rooms;
public BottleDrive()
{
rooms = new int[4];
}
static void Main(string[] args) //static is member of class not object
{
BottleDrive bD = new BottleDrive();
bD.getBottles();
bD.displayBottleCount();
bD.findWinner();
}
public void getBottles()
{
string quit = Console.ReadLine();
while while(quit != "quit")
{
int room = int.Parse(quit);
Console.Write("Bottles collected in room {0}: ", room);
rooms[room - 1] += int.Parse(Console.ReadLine());
Console.Write("Enter the room you're in: ");
}
}
public void findWinner()
{
int maxValue = 0;//initiates the winner, contructor starts at 0
int maxRoomNumber = 0;//initiates the room number that wins
for (int i = 0; i < rooms.Length; ++i)//This loop goes through the array of rooms (4)
{
if (rooms[i] > maxValue)//Makes sure that the maxValue is picked in the array
{//Looking for room number for the
maxValue = rooms[i];
maxRoomNumber = i + 1;
}
}
Console.WriteLine("And the Winner is room " + maxRoomNumber + "!!!");
}
public void displayBottleCount()
{
Console.WriteLine("Bottles collected in room one: " + rooms[0]);
Console.WriteLine("Bottles collected in room two: " + rooms[1]);
Console.WriteLine("Bottles collected in room three: " + rooms[2]);
Console.WriteLine("Bottles collected in room four: " + rooms[3]);
}
}
}
while (quit == "quit")
The above line will only run the loop if quit (what you got from the console) is "quit".
You want:
while (quit != "quit")
or
while (!quit.Equals("quit"))
After all that though you are also not actually updating quit inside your loop so once in you will never get out.
You'll need to capture your console.Readline and put it into "quit".
You probably also want to look at int.TryParse in case people type in a string that isn't quit or a valid integer. TryParse will tell you whether the parse was successful or not rather than throwing an exception.
This line:
while (quit == "quit")
should actually be:
while (quit != "quit")
Or better yet:
while (!quit.Equals("quit", StringComparison.CurrentCultureIgnoreCase))
Which will ignore case for the input. As others have noted, there's more issues with your loop. Try using this for your getBottles function:
public void getBottles()
{
string input;
do
{
Console.Write("Enter the room you're in: (or quit)");
input = Console.ReadLine();
int room;
// doing try parst because the input might be "quit" or other junk
if (int.TryParse(input, out room))
{
Console.Write("Bottles collected in room {0}: ", room);
// this will fail hard if the input is not of type int
rooms[room - 1] += int.Parse(Console.ReadLine());
}
} while (!input.Equals("quit", StringComparison.CurrentCultureIgnoreCase));
}
Should you have while(quit != "quit") for the while condition perhaps?
Try:
while (!quit.Equals("quit"))
The function getBottles() looks very strange. You only enter the while loop when you type "quit". I don't think that this is the behaviour you want.
Related
Hello I am trying to figure out why my program is not working, it's supposed to output a program in which department codes would be entered and followed by a prompt to enter a mark and so on until Q is entered. I can't seem to get that part working at all. If anyone could help please I will appreciate it.
// declare variables
char deptCode = ' ';
int count = 0;
double markVal, sum = 0, average = 0.0;
{
Console.WriteLine("Enter a department code: ‘C’ or ‘c’ for Computer Science,‘B’ or ‘b’ for History, ‘P’ or ‘p’ for Physics, or enter ‘Q’ or ‘q’ to quit:");
deptCode = Convert.ToChar(Console.ReadLine());
while (char.ToUpper(deptCode) != 'Q')
do
{
Console.Write("Enter a mark between 0 and 100 => ");
markVal = Convert.ToDouble(Console.ReadLine());
{
Console.WriteLine("Enter a department code: ‘C’ or ‘c’ for Computer Science,‘B’ or ‘b’ for History, ‘P’ or ‘p’ for Physics, or enter ‘Q’ or ‘q’ to quit:");
deptCode = Convert.ToChar(Console.ReadLine());
} while (markVal >= 0 && markVal <= 100);
count++;
average = (double)sum / count;
Console.WriteLine("***Error, Please Enter Valid Mark");
Console.WriteLine("The Average mark for Computer Science Students is {0}", average);
Console.WriteLine("The Average mark for Biology Students is {0}", average);
Console.WriteLine("The Average mark for Physics Students is {0}", average);
Console.ReadLine();
{
I am sympathetic to your dilemma and know it can be challenging to learn coding when you are not familiar with it. So hopefully the suggestions below may help to get you started at least down the right path. At the bottom of this is a basic “shell” but parts are missing and hopefully you will be able to fill in the missing parts.
One idea that you will find very helpful is if you break things down into pieces (methods) that will make things easier to follow and manage. In this particular case, you need to get a handle on the endless loops that you will be creating. From what I can see there would be three (3) possible endless loops that you will need to manage.
An endless loop that lets the user enter any number of discipline marks.
An endless loop when we ask the user which discipline to use
And an endless loop when we ask the user for a Mark between 0 and 100
When I say endless loop I mean that when we ask the user for a Discipline or a Mark… then, the user MUST press the “c”, “b” “p” or “q” character to exit the discipline loop. In addition the user MUST enter a valid double value between 0 and 100 to exit the Mark loop. The first endless loop will run allowing the user to enter multiple disciplines and marks and will not exit until the user presses the q character when selecting a discipline.
And finally when the user presses the ‘q’ character, then we can output the averages.
So to help… I will create two methods for you. One that will represent the endless loop for getting the Mark from the user… i.e.…. a number between 0 and 100. Then a second endless loop method that will get the Discipline from the user… i.e. … ‘c’, ‘b’, ‘p’ or ‘q’… and it may look something like…
private static char GetDisciplineFromUser() {
string userInput;
while (true) {
Console.WriteLine("Enter a department code: ‘C’ for Computer Science,‘B’ for Biology, ‘P’ for Physics, or enter ‘Q’ to quit:");
userInput = Console.ReadLine().ToLower();
if (userInput.Length > 0) {
if (userInput[0] == 'c' || userInput[0] == 'b' ||
userInput[0] == 'p' || userInput[0] == 'q') {
return userInput[0];
}
}
Console.WriteLine("Invalid discipline => " + userInput + " try again.");
}
}
Note… the loop will never end until the user selects the characters ‘c’, ‘b’, ‘p’ or ‘q’. We can guarantee that when we call the method above, ONLY those characters are returned.
Next is the endless loop to get the Mark from the user and may look something like…
private static double GetMarkFromUser() {
string userInput;
while (true) {
Console.WriteLine("Enter a mark between 0 and 100 => ");
userInput = Console.ReadLine().Trim();
if (double.TryParse(userInput, out double mark)) {
if (mark >= 0 && mark <= 100) {
return mark;
}
}
Console.WriteLine("Invalid Mark => " + userInput + " try again.");
}
}
Similar to the previous method, and one difference is we want to make sure that the user enters a valid number between 0 and 100. This is done using a TryParse method and most numeric types have a TryParse method and I highly recommend you get familiar with it when checking for valid numeric input.
These two methods should come in handy and simplify the main code. So your next issue which I will leave to you, is how are you going to store these values? When the user enters a CS 89 mark… how are you going to store this info? In this simple case… six variables may work like…
int totalsCSMarks = 0;
int totalsBiologyMarks = 0;
int totalsPhysicsMarks = 0;
double totalOfAllCSMarks = 0;
double totalOfAllBiologyMarks = 0;
double totalOfAllPhysicsMarks = 0;
Now you have something to store the users input in.
And finally the shell that would work using the methods above and you should see this uncomplicates things a bit in comparison to your current code. Hopefully you should be able to fill in the missing parts. Good Luck.
static void Main(string[] args) {
// you will need some kind of storage for each discipline.. see above...
char currentDiscipline = 'x';
double currentMark;
while (currentDiscipline != 'q') {
currentDiscipline = GetDisciplineFromUser();
if (currentDiscipline != 'q') {
currentMark = GetMarkFromUser();
switch (currentDiscipline) {
case 'c':
// add 1 to total number of CS marks
// add currentMarkValue to the total of CS marks
break;
case 'b':
// add 1 to total number of Biology marks
// add currentMarkValue to the total of Biology marks
break;
default: // <- we know for sure that only p could be left
// add 1 to total number of Physics marks
// add currentMarkValue to the total of Physics marks
break;
}
}
}
Console.WriteLine("Averages ------");
//Console.WriteLine("The Average mark for Computer Science Students is {0}", totalOfAllCSMarks / totalCSMarks);
//Console.WriteLine("The Average mark for Biology Students is {0}", ...);
//Console.WriteLine("The Average mark for Physics Students is {0}", ...);
Console.ReadLine();
}
I am in my second week of C# training, so I am pretty new to programming. I have to make a program that returns the smallest integer out of a series of random integer inputs. Once the input = 0, the program should break out of the loop. I am only allowed to use while and for loops. For some reason my program breaks out of loop after the second input and it looks like it doesn't even care if there is a "0" or not. Could you please see where I went wrong? I have been busting my head off with this. Sorry if this question has already been posted by somebody else but I did not find an answer to it anywhere.
PS: The zero input should be taken into account for the comparison.
So this is what I've got so far:
class Program
{
static void Main()
{
int i = 0;
int input = Int32.Parse(Console.ReadLine());
int min = default;
while (input != 0)
{
Console.ReadLine();
if (i == 0)
{
min = input;
break;
}
if (input < min && i !=0)
{
input = Convert.ToInt32(Console.ReadLine());
min = input;
}
i++;
}
Console.WriteLine(min);
}
First of all you will want to re-read the documentation for for- and while-loops. There are several useful pages out there.. e.g. for / while.
Problem
The reason why your loop breaks is that you initialize i with 0.
int i = 0;
Inside your loop you are using the if-statment to break the loop if the condition "i is 0" is met.
if (i == 0)
{
min = input;
break;
}
The input that the user has to provide each iteration of the loop is ignored by your program as you are never storing this kind of information to any variable.
while (input != 0)
{
Console.ReadLine();
// ...
}
Possible Solution
As a beginner it is helpful to tackle tasks step by step. Try to write down each of this steps to define a simple algorithm. As there are many solutions to this problem one possible way could be:
Declare minimum value + assign max value to it
Use a while loop and loop till a specific condition is matched
Read user-input and try converting it to an integer
Check whether the value is 0 or not
4.1. If the value is 0, go to step 8
4.2. If the value is not 0, go to step 5
Check whether the value is smaller than the current minimum value
5.1. If the value is smaller, go to step 6
5.2. If the value is not smaller, go back to step 3
Set the new minimum
Go back to step 3
Break the loop
End program
A program that handles the above steps could look like:
using System;
namespace FindMinimum
{
public class Program
{
static void Main(string[] args)
{
// Declare minimum value + assign initial value
int minValue = int.MaxValue;
// Loop until something else breaks out
while (true)
{
Console.WriteLine("Please insert any number...");
// Read io and try to parse it to int
bool parseOk = int.TryParse(Console.ReadLine(), out int num);
// If the user did not provide any number, let him retry
if (!parseOk)
{
Console.WriteLine("Incorrect input. Please insert numbers only.");
continue;
}
// If the user typed in a valid number and that number is zero, break out of the loop
if (parseOk && num == 0)
{
break;
}
// If the user typed in a valid number and that number is smaller than the minimum-value, set the new minimum
if (parseOk && num < minValue)
{
minValue = num;
}
}
// Print the result to the console
Console.WriteLine($"Minimum value: {minValue}.");
// Keep console open
Console.ReadLine();
}
}
}
Try This:
int input;
Console.Write("Enter number:");
input = Int32.Parse(Console.ReadLine());
int min = input;
while(true)
{
if (input == 0)
break;
if (min > input)
min = input;
Console.Write("Enter number:");
input = Int32.Parse(Console.ReadLine());
}
Console.WriteLine(min);
Console.ReadKey();
I hope it helps.
Sorry if this isn't the right. This is my first time posting here. I'm a first year Software student and for the life of me i cannot seem to get this to work. I know its something simple I'm missing but oh well. I tried doing this using methods but again no help. Maybe you guys could help me?
The problem is the code wont let me input after the "Are you a member (Y/N)" writline statement and just keeps giving me an output of 50.
static void Main(string[] args)
{
//Local Variable Declaration//
double rate1 = 10;
double rate2 = 3;
double maxCharge = 50;
double charge;
Console.WriteLine("Enter number of hours (-999 to quit) : ");
int hoursRented = Console.Read();
if (hoursRented >= 3)
{
charge = hoursRented * rate1;
}
else
{
charge = (3 * rate1) + (hoursRented * rate2);
}
if (charge > maxCharge)
{
charge = maxCharge;
}
Console.WriteLine("Are you a member? (Y/N) : ");
int memberStatus = Console.Read();
if (memberStatus.Equals("Y"))
{
charge = (charge * 1 / 10) - charge;
}
Console.WriteLine("Customer Charge : {0} Total Charge To Date : ", charge);
}
The problematic lines are below
Console.WriteLine("Enter number of hours (-999 to quit) : ");
int hoursRented = Console.Read();
if (hoursRented >= 3) {
and
Console.WriteLine("Are you a member? (Y/N) : ");
int memberStatus = Console.Read();
if (memberStatus.Equals("Y")) {
When you call Console.Read(), it reads only characters and returns it as an int. You seem to mistakenly think it will parse the character to an int.
Secondly, think what happens when you provide multiple characters as input to a single Console.Read() call. Interestingly, the remaining characters are read in the subsequent calls. So when you type any number followed by Enter in the first Console.Read it only, reads the first character, the subsequent characters, including the EOLN char are returned in the subsequent calls, instead of prompting you to enter information for the next call.
The fix is easy. Use Console.Readline() and int.parse (or its int.TryParse() variant
Then the corresponding code will look like below
Console.Write("Enter number of hours (-999 to quit) : ");
string hoursRentedStr = Console.ReadLine();
int hoursRented = int.Parse(hoursRentedStr);
if (hoursRented >= 3) {
and
Console.Write("Are you a member? (Y/N) : ");
string memberStatus = Console.ReadLine();
if (memberStatus.Equals("Y")) {
This is because you are just writing:
Console.WriteLine("Are you a member? (Y/N) : ");
and continuing through.
you must do it like this:
Console.WriteLine("Are you a member? (Y/N) : ");
Console.ReadLine();
and then:
int memberStatus = Int.Parse(Console.ReadKey());
your problem is that your are using Console.Read wich returns the ascii code of the next charachter as said by #juharr in the comments. so the solution is too simply replace Read By ReadLine and change your code like this, so that ReadLine wich is a string will be converted to the int value that you want
int hoursRented = int.Parse(Console.ReadLine());
And change your member status to a string to compare it with "Y" easily
string memberStatus = Console.ReadLine();
Note: if you want to validate the input you should use a int.TryParse instead of just a normal parse like I used as it returns a bool so you knows when it fails
I am writing a program for class and need some advice on how to get it working. I have a program that calls for the user to input the price of an item. Once they enter the price for the first item then it asks them for the next price. The problem is that I need it in a do-while loop. I am trying to get the total price for the items entered after each instance of the while loop. I know i could use an array or list but the assignment doesn't call for this.
Any advice would be helpful.
Here is the code for the do while loop.
public static void Main()
{
double cost;
int Items;
string counter;
string value;
string more;
double newtotal;
int loopcounter = 0;
//item cost
Console.WriteLine("Welcome to the Online Store");
Console.WriteLine("How many items are you buying?");
counter = Console.ReadLine();
Items = Convert.ToInt32(counter);
do
{
// buying items
Console.WriteLine("Enter the cost of your item one by one");
value = Console.ReadLine();
cost = Convert.ToDouble(value);
newtotal = +cost;
loopcounter++;
}
while (loopcounter < Items);
write below code after newtotal = +cost; statement into do while : Console.WriteLine("your total amount : {0} ",newtotal);
newtotal=+cost; is wrong
instead type newtotal+=cost;
Move
Console.WriteLine("Enter the cost of your item one by one");
out from the loop since you don't have to tell the buyer to enter one by one again and again...
Good keep it up
I've developed a new found interest in programming however I have had some problems. I have tried to make a simple program in which a user enters 10 numbers, if the number is 0 it will stop, then adds those numbers to a list then prints the list at the end. However, my program only asks for 4 numbers before stopping, it doesn't stop when 0 is entered and the "Enter a number message" at the start prints 3 times each time it goes round the loop.
Any help would be appreciated
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args) {
// I want to make a list
// keep asking the user for values
// which will then add those values onto the list
// then print the list
// create a list
List<int> list = new List<int>();
int count = 0;
while (count < 10) {
Console.WriteLine("Enter a value to add to the list");
int number = Console.Read();
list.Add(number);
if (number == 0) {
break;
}
count++;
}
Console.WriteLine("The final list looks like this");
foreach (int number in list) {
Console.WriteLine(number);
Console.ReadLine();
}
}
}
}
The problem is with Console.Read() - It reads a byte rather than a string that should be converted into int in your case.
What you're looking for is Console.ReadLine(), surrounded with int.Parse(). Something like this:
int number = int.Parse(Console.ReadLine());