Hi I’m new to C# and I am trying to build a very simple stock tracking console application where a user inputs some info about a stock and the program saves and uses the input. I’ve been going through online tutorials but I cannot seem to put it all together.
I want to ask a user to choose whether they want to sell a stock, buy a stock, or exit the program. If they choose buy or sell a stock the program will ask them to enter the stock ticker, amount of stock purchased and price paid.
In this case I want the user to be able to continue to buy stock or sell stock until they choose to exit the application. The program should track the total amount of stock the user has for each ticker. For example, the user can input they purchased 100 shares of APPL stock on 2/1/12, then enter they purchased an additional 50 shares of APPL stock on 2/15/12, and then sold 25 shares of APPL stock on 3/1/12.
The program will track the info and when the user chooses to exit, the program will output how many shares they have left. In the above example they have 125 shares left.
Eventually I want to turn this into a real-time stock trading program, but for now I'm just taking baby steps.
I have include the code I have written so far below. I don't understand the best way to handle the user input.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
namespace StockTracker
{
class Program
{
static void Main(string[] args)
{
while (true)
{
Console.WriteLine("Welcome to the Stock Tracker");
Console.WriteLine("--------------------------------");
Console.WriteLine("Please choose from the following options:");
Console.WriteLine("1) Buy Stock, 2) Sell Stock, 0) Exit");
ArrayList Array1 = new ArrayList();
ArrayList Array2 = new ArrayList();
string userValue = Console.ReadLine();
string message = "";
double price;
int amount;
string stockTicker;
switch (userValue)
{
case "1":
Console.WriteLine("Enter ticker to buy:");
stockTicker = Console.ReadLine();
Array1.Add(stockTicker);
Console.WriteLine("Enter stock price");
price = double.Parse(Console.ReadLine());
Array1.Add(price);
Console.WriteLine("Enter Quantity");
amount = int.Parse(Console.ReadLine());
Array1.Add(amount);
Console.WriteLine("***Stock Purchased***");
break;
case "2":
//message = "Enter stock ticker to sell";
Console.WriteLine("Enter stocker ticker to sell");
stockTicker = Console.ReadLine();
Array2.Add(stockTicker);
Console.WriteLine("Enter Quantity");
amount = int.Parse(Console.ReadLine());
Array2.Add(amount);
Console.WriteLine("***Stock Sold***");
break;
case "0":
Console.WriteLine("Good Bye!");
return;
default:
message = "Invalid entry";
break;
}
Console.Write(message);
Console.ReadLine();
Console.WriteLine();
} //while (userValue != "0");
}
}
}
You need to think about what your requirements are exactly. Do you need to track every trade? Or just the total of each stock? Do you want this information to be persistent?
If you just what to keep track of the total number of each stock, I'd suggest using a Dictionary instead of your ArrayLists. Something like this:
Dictionary<string,int> myStocks = new Dictionary<string,int>();
//....
case "1":
Console.WriteLine("Enter ticker to buy:");
stockTicker = Console.ReadLine();
Console.WriteLine("Enter stock price");
price = double.Parse(Console.ReadLine());
Console.WriteLine("Enter Quantity");
amount = int.Parse(Console.ReadLine());
int currAmount = 0;
myStocks.TryGetValue(stockTicker,out currAmount);
myStocks[stockTicker] = currAmount + amount;
Console.WriteLine("***Stock Purchased***");
break;
If you really need to track both the name and amounts separately, you should create a class (call it Trade) that has properties for stock symbol, amount, price, date, etc and store those in a List<Trade>.
Related
I have a private method named RentingOrBuying(); that gathers information about the property price and interest rate. I want to create another private method that calculates the monthly home loan repayment but I need the information in RentingOrBuying().
Ive tried using get and set methods but the initialization doesn't seem to work. Maybe I did it wrong. Any help is appreciated. I am calling all the methods in the main class. Is it worth leaving them private or should I be making the methods public. How would you go about this?
//this method uses the information gathered in RentingOrBuying and calculates the monthly home loan repayment
private static void CalculateMonthlyLoanAmount()
{
//accumulated amount = propertyPrice(1 + interestRate)^monthsToRepay
double repaymentAmount = propertyPrice(1 + interestRate);
}
//A method that asks whether the user is buying or renting accommodation and gathers necessary information
private static void RentingOrBuying()
{
Console.WriteLine("Are you going to be renting accommodation or buying a property? \n Please enter either [rent] or [buy]");
//variable to store user input
string buyingRenting = Console.ReadLine();
if (buyingRenting.ToLower() == "rent")
{
Console.WriteLine("We see you want to rent, please can you enter the monthly rental amount: ");
//variable that stores the monthly rental amount.
double monthlyRental = double.Parse(Console.ReadLine());
}
else
{
Console.WriteLine("So you've chosen to buy, I will just need the following ionformation:");
Console.WriteLine("Please enter the purchase price of property: ");
//variable stores the price of the property the user wants to buy
double propertyPrice = double.Parse(Console.ReadLine());
Console.WriteLine("Please enter the total deposit: ");
//variable stores the total deposit
double totalDeposit = double.Parse(Console.ReadLine());
Console.WriteLine("Please enter the interest rate (percentage): ");
//variable store the interest rate in percentage form
int interestRate = Int32.Parse(Console.ReadLine());
Console.WriteLine("Please enter the number of months to repay: ");
//variable stores the amount of months to repay
int monthsToRepay = Int32.Parse(Console.ReadLine());
}
}
you should take any variables needed as input parameters, and return any results from the calculations, i.e.
private static double CalculateMonthlyLoanAmount(double interestRate, double propertyPrice)
{
// do whatever calculation you need do to here
// return the result
return result;
}
More complex scenarios would involve encapsulating the variables in a class, to avoid needing to specify them if you call a method multiple times, or multiple methods share many of the variables.
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 5 years ago.
Improve this question
I am doing my homework. English is not my first language, so I am confused.
This is the question: Write a program that computes the average of five exam scores. Declare and perform a compile-time initialization with the five exam values. Declare integer memory locations for the exam values. Use an integer constant to define the number of scores. Print all scores. The average value should be formatted with two digits to the right of the decimal. Rerun the application with different values. Be sure to desk check your results.
I am not sure what is "a compile-time initialization" mean? What is "Declare integer memory locations for the exam values." want me to do? What is "desk check" mean?
Here is my c# code:
using System;
using static System.Console;
namespace Chap2_1
{
class Chap2_1
{
static void Main()
{
int score1;
int score2;
int score3;
int score4;
int score5;
double average;
Console.Write("Please enter the 1st score: ");
score1 = Convert.ToInt32(Console.ReadLine());
Console.Write("Please enter the 2nd score: ");
score2 = Convert.ToInt32(Console.ReadLine());
Console.Write("Please enter the 3rd score: ");
score3 = Convert.ToInt32(Console.ReadLine());
Console.Write("Please enter the 4th score: ");
score4 = Convert.ToInt32(Console.ReadLine());
Console.Write("Please enter the 5th score: ");
score5 = Convert.ToInt32(Console.ReadLine());
average = (score1+score2+score3+score4+score5) /5;
Console.Write("Average score is " + "{0:N2}", average);
Console.ReadKey();
}
}
}
I am not sure what is "a compile-time initialization" mean?
It means that your scores should have a value set in code from the start (hard coded), rather than values set by user input or "figured out" by the program after it's already running.
In other words, replace this:
Console.Write("Please enter the 1st score: ");
score1 = Convert.ToInt32(Console.ReadLine());
Console.Write("Please enter the 2nd score: ");
score2 = Convert.ToInt32(Console.ReadLine());
Console.Write("Please enter the 3rd score: ");
score3 = Convert.ToInt32(Console.ReadLine());
Console.Write("Please enter the 4th score: ");
score4 = Convert.ToInt32(Console.ReadLine());
Console.Write("Please enter the 5th score: ");
score5 = Convert.ToInt32(Console.ReadLine());
With something like this:
//Replace the pointed numbers with whatever the scores should be.
// ||
// vv
score1 = 11;
score2 = 22;
score3 = 33;
score4 = 44;
score5 = 55;
What is "Declare integer memory locations for the exam values."
It means declaring the variables responsible for holding the scores so that you can average them. In other words, this part:
int score1;
int score2;
int score3;
int score4;
int score5;
What is "desk check" mean?
It means that you should average the scores with pen & paper, and make sure the result your program outputs is correct.
PS: I don't want to be rude, but this community is made for questions about code. If you don't understand the question, or english in general, you should ask your teacher.
We are here to help you with programming... not with translation or interpretation.
Shouldn't these be questions for your teacher? Your teacher will know your struggles and be able to help you far better than any of us simply because of his/her role in your studies.
That said, a compile-time initialization is something like:
int[] scores = new int[] { 100,80,90,64,72 };
or:
int score1 = 100;
int score2 = 80;
int score3 = 90;
int score4 = 64;
int score5 = 72;
As far as the memory locations go, I'd recommend reading Microsoft's C# programming guide here about it:
https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/unsafe-code-pointers/how-to-obtain-the-address-of-a-variable
Oh, and "desk check" means to do the same calculations manually with pen and paper to validate that you get the same results as your code.
Fill array with user input but not using for loop, because the user need to select when to enter the data.
for loop will not be useful here because I'm not trying to let the user enter all the input at once, but when the user chooses to via switch statement.
I don't know if this makes any sense, new here, excuse my unprofessional language.
static void AddChemical(string[] ChemicalName, string[] Supplier, int[] YearPurchased, int[] Toxicty, int[] Flammability, int[] Corrosiveness, int[] Explosive, int[] Harmful, int[] Overall, float[] Quantity, float[] Cost)
{
int Count = 0;
Count = Count + 1;
Console.Write("Enter the name of the Chemical: ");
ChemicalName[Count] = Console.ReadLine();
Console.Write("Enter the year it was Purchased: ");
int.TryParse(Console.ReadLine(), out YearPurchased[Count]);
Console.Write("Enter the Supplier of the Chemical: ");
Supplier[Count] = Console.ReadLine();
Console.Write("Enter the Quantity of the Chemical in (L/Kg): ");
float.TryParse(Console.ReadLine(), out Quantity[Count]);
Console.Write("Enter the cost of the Chemical: ");
float.TryParse(Console.ReadLine(), out Cost[Count]);
Console.Write("Enter the Toxicty of the Chemical: ");
int.TryParse(Console.ReadLine(), out Toxicty[Count]);
Console.Write("Enter the Flammability of the Chemical: ");
int.TryParse(Console.ReadLine(), out Flammability[Count]);
Console.Write("Enter the Corrosiveness of the chemical: ");
int.TryParse(Console.ReadLine(), out Corrosiveness[Count]);
Console.Write("Enter the Explosive of the Chemical: ");
int.TryParse(Console.ReadLine(), out Explosive[Count]);
Console.Write("Enter the Harmful of the Chemical: ");
int.TryParse(Console.ReadLine(), out Harmful[Count]);
}
This method is inside a switch statement.
I Really Have no idea what you are trying to do, but if you are talking about entering all the inputs into a array but not in the same time you can use collections.
first you need to use the nampspace
using System.Collections
Then Create a new Collection that holds on your results
ArrayList dataHolder = new ArrayList();
Then Whenever you need to add Something to it just type this code
dataHolder.Add("We are adding a string");
dataHolder.Add(21) // Adding a Number
and you can get them letter by index
Console.WriteLine(dataHolder[1]); // Outputs 21
BTW this is really non-efficient way of writing the code but i am just helping you out ;)
This is my first question so I apologize if there are errors. I am very new to C# and in my first question. This is a excerpt from the assignment that was tasked to me:
The program should ask the user to enter the
charge for the meal, the tax rate (as a percent of 100), and if the user wants to tip by percent (%) or
amount ($). If tipping by percent, ask the user to choose one of the following options:
10%
15%
20%
Custom
The Custom option will ask the user to enter the tip percent that is calculated before adding the tax. If the user chooses to tip by amount, then ask the user to enter the tip amount. Display the meal charge, tax amount, tip amount (tip percent), and total bill on the screen.
I have the Tax and the outputs down. But I am stuck on the Tip preference and the choosing between the different percentages and custom. Any help would be appreciated thanks very much.
Edit: This is just to output on the console and all of the code can just be done on the main. The instructions want me to enter 1 or 2 for choosing between percent and amount, and 1-4 for the different percantages
Display all options to the user and ask the user to choose between them. The program will ensure the input is valid and that the input corresponds to a valid option, like so:
int ReadInt(Int32 min, Int32 max) {
while( true ) {
Console.WriteLine("Please enter an integer between {0} and {1} (inclusive).", min, max);
Int32 value;
if( Int32.TryParse( Console.ReadLine(), out value ) ) ) return value;
}
}
static void Main() {
// ...
Console.WriteLine("[1] - 10%");
Console.WriteLine("[2] - 15%");
Console.WriteLine("[3] - 20%");
Console.WriteLine("[4] - Custom");
Console.WriteLine("Select a tip option.");
Int32 opt = ReadInt( 1, 4 );
Int32 tipAmount;
switch( opt ) {
case 1: {
tipAmount = 10;
break;
}
case 2: {
tipAmount = 15;
break;
}
case 3: {
tipAmount = 20;
break;
}
case 4: {
Console.WriteLine("Enter an integer tip percentage value:");
tipAmount = ReadInt( 0, 100 );
break;
}
default: throw new InvalidOptionException("Impossible user input.");
}
Decimal tipAmount = ( ( (Decimal)tipAmount ) / 100.0M ) * invoiceAmount;
Console.WriteLine("Please pay {0:C} to the waitstaff as compensation for their institutional labor exploitation.");
// ...
}
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 8 years ago.
Improve this question
I have written up to this place and am stuck I need help on how to terminate a program or continue .
What I mean is that when I ask the question would you like to withdraw today and if their response is NO then the program should terminate but if its YES it should continue.
What am I missing?
Please implement the aspect where by the program should terminate using the N for NO statement i didn't received the answer to that.
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
int amount = 20000;
int choice, pin = 0, x = 0;
Console.WriteLine("Enter your pin");
pin = int.Parse(Console.ReadLine());
Console.WriteLine("welcome to HSPUIC bank would you like to make a withdraw today N or Y");
Console.ReadLine();
}
}
}
You are on the right track. What you are missing is to take and evaluate the user input - this is the information returned by the Console.ReadLine method (as mentioned in the comments) like this:
line = Console.ReadLine();
Your code could look like this:
int amount = 20000;
int choice, pin = 0, x = 0;
Console.WriteLine("Enter your pin");
pin = int.Parse(Console.ReadLine());
Console.WriteLine("welcome to HSPUIC bank would you like to make a withdraw today N or Y");
// save user input
var userInput = Console.ReadLine();
// evaluate if user wants to continue or not
if (userInput.ToLower() == "y")
{
// if yes, go further
Console.WriteLine("continue with other action...");
}
// else bye
Console.WriteLine("goodbye");
The line for the PIN already uses the user input! The same can be done with the question. If you want to stay in the loop until the user does not want to withdraw any more, than you need more than if-else. Take a look at the iteration statements like do and while.
A solution could look like this:
// user input = y or n
string choice;
// user pin
int pin = 0;
// state that indicates if the user wants to continue or not
bool continueLoop = false;
do
{
// greet user
Console.WriteLine("welcome to HSPUIC bank would you like to make a withdraw today N or Y");
// take input
choice = Console.ReadLine();
// check if user has entered valid input
if (choice.ToLower() == "y" || choice.ToLower() == "n")
{
// default decision is "user does not want to continue" = exit
continueLoop = false;
// user has choosen to continue
if (choice.ToLower() == "y")
{
// user wants to do something, so stay in the loop
continueLoop = true;
// ask for pin
Console.WriteLine("Enter your pin");
var pinAsText = Console.ReadLine();
// convert the pin to number: if (int.TryParse(pinAsText, out pin)) ...
if (pinAsText == "1234")
{
Console.WriteLine("PIN correct");
// continue with logic here, for example take amount
}
else
{
Console.WriteLine("PIN incorrect");
}
}
}
else
{
Console.WriteLine("Please enter Y or N");
continueLoop = true;
}
} while (continueLoop);
Console.WriteLine("goodbye");
Now the flow looks like this:
welcome to HSPUIC bank would you like to make a withdraw today N or Y
>> Y
Enter your pin
>> 3
PIN incorrect
welcome to HSPUIC bank would you like to make a withdraw today N or Y
>> Y
Enter your pin
>> 1234
PIN correct
welcome to HSPUIC bank would you like to make a withdraw today N or Y
>> N
goodbye
Certainly when your users have two different choice , you should use if in your program . Also you should save user's answer into a local variable to process it .
static void Main(string[] args)
{
int amount = 20000;
int choice, pin = 0, x = 0;
Console.WriteLine("Enter your pin");
pin = int.Parse(Console.ReadLine());
Console.WriteLine("welcome to HSPUIC bank would you like to make a withdraw today N or Y");
char answer = char.Parse(Console.ReadLine());
if (answer == 'Y')
{
//Code that must be executed after choosing "yes" .
Console.ReadKey();
}
}
When you write nothing for "no" , your program will terminate .
Also you can use string instead of char :
string answer = Console.ReadLine();
if (answer == "Y")
{
//Code that must be executed after choosing "yes" .
Console.ReadKey();
}
By the way, there are a lot of possible errors in your code (e.g. enter a character instead of integer for variable ' pin ') that must be handled by try-catch.