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
Related
I made a foreach loop that would take a user's input and subtract two numbers on the same line, I was hoping it would print out the difference between any two numbers, but it didn't. Instead, when I ran the code and entered the numbers, it printed a different answer which didn't make sense to me. I'm kind of a bit new to c# so I'm just experimenting with things, but if anyone knows what's wrong with my code please help me figure out what's wrong with it. Thanks!
using System;
public class Program
{
string sequence;
double answer;
public void Main()
{
Console.WriteLine("<<SUBTRACTION CODE>>");
Console.WriteLine("");
Console.WriteLine("Enter a sequence of numbers and an operator to get subtracted answer ");
Console.WriteLine("Eg: 10-5");
sequence = Console.ReadLine();
foreach (var operation in sequence.Split('-'))
{
answer -= double.Parse(operation);
}
Console.WriteLine(answer);
Console.ReadLine();
}
}
your answer will initially be 0. So when you do answer -= you subtract the right-hand-site (e.g. 5) from zero, which will result in a negative outcome. I suppose you need to assign the first operat to your answer:
using System;
public class Program
{
string sequence;
double answer;
public void Main()
{
Console.WriteLine("<<SUBTRACTION CODE>>");
Console.WriteLine("");
Console.WriteLine("Enter a sequence of numbers and an operator to get subtracted answer ");
Console.WriteLine("Eg: 10-5");
sequence = Console.ReadLine();
var parts = sequence.Split('-');
answer = parts[0];
for(int i = 1; i < parts.Length; i++)
{
answer -= double.Parse(parts[i]);
}
Console.WriteLine(answer);
Console.ReadLine();
}
}
Of course you should check if there are at least two elements within parts.
Assuming you want 5 rather than -15?
You need to initialise the value of answer with the first number rather than subtract everything from a starting point of zero.
bool init;
string sequence;
double answer;
public void Main()
{
Console.WriteLine("<<SUBTRACTION CODE>>");
Console.WriteLine("");
Console.WriteLine("Enter a sequence of numbers and an operator to get subtracted answer ");
Console.WriteLine("Eg: 10-5");
sequence = Console.ReadLine();
foreach (var operation in sequence.Split('-'))
{
if (!init) {
answer = double.Parse(operation);
init = true;
}
else
answer -= double.Parse(operation);
}
Console.WriteLine(answer);
Console.ReadLine();
}
I am trying to create an array that holds prices that the user inputs into the command prompt.
This is what I have so far
using System;
using static System.Console;
namespace Chapter6._2
{
class Program
{
static void Main()
{
int price;
int[] pricesList = new int[9];
Write("Enter price 1: ");
price = Read();
}
}
}
Also how would I create a loop to where it asks for the price of an item 10 times but goes something like this...
"Enter price 1: < user input price >"
"Enter price 2: < user input price >"
"Enter price 3: < user input price >"
and etc...Hopefully that makes sense.
Basically with these 2 questions I have asked, how would I create a loop where the program asks the user for prices 10 times, and stores the prices in an array and prints the total of all of the prices entered into the program at the end.
You need to use a for loop, cycling many times as your array length. Each iteration will ask the user for the Nth price, store it in the Nth position of the array and add the price to some "sum" variable. Also maybe you want to check System.Convert class.
This is as far I can go without doing your homework for you.
Please read this before asking more school related stuff:
How do I ask and answer homework questions?
Think of using a for loop. Your condition should be like i <= pricesList.Length
You can ask for user input as something like this: Console.WriteLine("Enter price {0}", i); or Console.WriteLine("Enter price {0}", i+1); if you want to start with 1 and not 0.
See array loops here C# arrays
I'm trying to assign user given names into name variables (Player1, Player2, etc).
The amount of players the program asks for is dependent on the amount the user gives (int TotalPlayers). So if the user says the total to be 5, then the for loop would ask for 5 names and not more.
Im trying to achieve this by first adding all user inputs into a list and then assigning the names in the list into Name Variables later but I can't seem to make this work.
Can someone help me fix the errors or is there a better way to go about doing this?
Thanks!
Console.WriteLine("Write amount of players");
int TotalPlayers = Convert.ToInt32(Console.ReadLine());
List<string> PlayerList = new List<string>();
for (int players = 0; players < TotalPlayers; players++)
{
Console.WriteLine("Enter player {0}'s name:", players + 1);
PlayerList.Add(Console.ReadLine());
}
Console.WriteLine(PlayerList);
the code above looks to be executing correctly but I think we need some more information. What does your name variable look like? if you wanted you can just create a list of those through the loop like so.
say NameVariable is some simple object.
public class NameVariable
{
public int id {get;set;}
public string Name {get;set;}
}
Then your code would look something like:
public static void Main()
{
Console.WriteLine("Write amount of players");
int TotalPlayers = Convert.ToInt32(Console.ReadLine());
List<NameVariable> PlayerList = new List<NameVariable>();
for (int index = 0; index < TotalPlayers; index++)
{
Console.WriteLine("Enter player {0}'s name:", index + 1);
PlayerList.Add(new NameVariable(){
Name = Console.ReadLine(),
Id = index
});
}
foreach(var player in PlayerList)
{
Console.WriteLine(player.Name);
}
}
Looks like it's the Console.WriteLine(PlayerList); that is causing you problems.
This uses the built-in ToString method from the base object which will give you
System.Collections.Generic.List`1[System.String]
Or similar.
You can try Console.WriteLine(string.Join(", ", PlayerList)); to get a simple string list.
Most of the time, the default string generation in .Net is not what you want, and you will need to loop over your list and build the string yourself.
I need a little help sorting a split array into highest to lowest while keeping the names next to the scores. Im a little unsure how to do so because the array is split. Also, is there a way to let the user enter as many names and scores as they want without the program giving the user an error? So if they only want to enter 4 names and scores, all they have to do is press enter?
This is the code I have so far.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace proj09LEA
{
class Program
{
static void Main(string[] args)
{
// declare and array of integers
string[] name = new string[5];
int[] score = new int[5];
Console.WriteLine("\nSaturday Coder's Bowling Team");
Console.WriteLine("Enter in a name and score for each person on the team.");
Console.WriteLine("For example, Mary 143. Just hit Enter when you are done.\n");
// fill an array with user input
for (int i = 0; i < score.Length; i++)
{
Console.WriteLine("Enter in a name and score: ");
string line = Console.ReadLine();
name[i] = line.Substring(0, line.IndexOf(' '));
score[i] = int.Parse(line.Substring(line.IndexOf(' ') + 1));
}
Console.WriteLine("------------ Input Complete ------------\n");
Console.WriteLine("Here are the scores for this game, from highest to lowest:\n");
for (int i = 0; i < score.Length; i++)
{
if (score[i] >= 300)
{
Console.WriteLine("{0}'s score was {1}*.", name[i], score[i]);
}
else
{
Console.WriteLine("{0}'s score was {1}.", name[i], score[i]);
}
}
AverageScore(score);
Console.WriteLine("Press Enter to continue. . .");
Console.ReadLine();
}
static void AverageScore(int[] score)
{
int sum = score.Sum();
int average = sum / score.Length;
Console.WriteLine("The average score for this game was {0:d}.\n", average);
}
}
}
Let me first address the infinite-players question. Arrays, as you know, have a size, fixed at creation. There’s a data structure, List, though, that can have an unbounded (well, practically) number of elements. You might create one like this:
List<string> names = new List<string>();
Then if you want to add a new name, you can, for example, use
names.Add("Mary");
The rest of your code should work about the same; indexing works as normal, summing works as normal, etc.
Now what about sorting both of them together? Well, you don’t really have a list of names and a list of scores; what you really semantically have is a list of pairs of names and scores, or a list of players. You could first define a structure that represents a player:
struct Player {
public string Name { get; set; }
public int Score { get; set; }
public Player(string name, int score) {
Name = name;
Score = score;
}
}
Then you could just have a list of players:
List<Player> players = new List<Player>();
Instead of adding names and scores separately, we add them together:
string name = /* ... */;
int score = /* ... */;
players.Add(new Player(name, score));
Represented like this, your printing routine also becomes simpler. You can iterate through both at once:
foreach(Player player in players) {
Console.WriteLine("{0} scored {1}", player.Name, player.Score);
}
Lastly, summing is a little trickier, but not too hard. Basically, we extract all of the scores and sum those:
int sum = players.Select((player) => player.Score).Sum();
But for you, the real benefit is finally being able to sort it:
players.Sort((x, y) => y.Score - x.Score);
What you basically need is to take a look at HashMaps which are ADT's specifically for this purpose. Their structure is as follows:
-key1 : value1
-key2 : value2
.....
-keyn : valuen
your key here should be your score (but it can be anything). The value will be the name associated to the score.
Then , you can create a method sortKeys, depending on your implementation, which would take each key in the HashMap, move it at the end or at the beginning, while pointing to your name.
But please note that some HashMaps are randomly stored, so you will have to possibly make an array to write the sorted order of keys (and then lookup the key's value in the HashMap).
sort the array first using the Arrays.sort method then loop from
for(int i= x.length-1;i>=0;i--)
System.out.print(x[i]+"");
Should work this way
List would be a better option and these come in built sorting options that would make your task easier.
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.