Simulating the rise and fall of the Stock Market java - java

So I'm trying to write a program that stimulates the rise and fall of the Stock market 5 times.The user inputs a value to create a new Stock Market Object then with the value from the user, the stock market either is a bust(decrease) or a boom( increase). The issue I'm having is passing the value to each if statement with the change within the loop.When I run the program, It uses the same value I entered instead of using the value that was created after calling boom or bust. I'm thinking I should create a value outside the loop that holds it but I'm not sure how to do that with the user input.
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Enter a Starting Market Value:");
double mv = in.nextDouble();
StockMarket u = new StockMarket(mv);
for (int i = 0; i < 5; i++) {
System.out.println("Boom (1) or Bust(2)? ");
int t = in.nextInt();
if (t == 1) {
System.out.println("Enter a percentage of increase as a decimal ( eg .5 ):");
double r = in.nextDouble();
if (t == 1) {
double e = u.boom(r);
System.out.println("The Stock Market is now at: " + e);
}
} else if (t == 2) {
System.out.println("Enter number of points lost:");
double l = in.nextDouble();
if (t == 2) {
double f = u.bust(l);
System.out.println("The Stock Market is now at: " + f);
}
}
}
}
}
Below is the class
public class StockMarket {
//Instance Variable Points
private double Points;
// Default no Argument Constructor
public StockMarket(){
this(0.0);
}
// Constructor #2
public StockMarket(double Points){
this.Points = Points;
}
//
public double getPoint(){
return Points;
}
public double boom(double x){
x = Points * (1 + x);
return x;
}
public double bust( double h){
h = Points - h;
return h;
}
}

Related

List within an arraylist issue

I have the code below:
package Main; import java.util.*;
public class Generator {
List <List<String>>masterList = new ArrayList<List<String>>();
ArrayList memberList = new ArrayList<String>();
String leaderName, memberName;
int numLeaders, numMembers;
double x;
Scanner scanner = new Scanner(System.in);
// This program takes in total number of people first
// Then takes in number of leaders to assign peoples to
// Then takes in people to be assigned
// And then assigns people to given leaders randomly
public int getNumLeader() {
System.out.println("How many leaders are there??");
numLeaders = scanner.nextInt();
return numLeaders;
}
public void setNumLeader(int numLeaders) {
this.numLeaders = numLeaders;
}
public int getNumMembers() {
System.out.println("How many members are there?");
numMembers = scanner.nextInt();
return numMembers;
}
public void setNumMembers(int numMembers) {
this.numMembers = numMembers;
}
public void genLeaders() {
System.out.println("Please type the name of the leader on the following:");
for (int i = 1; i <= numLeaders; i++) {
if (i == numLeaders) {
System.out.println("What is the last leader's name?");
leaderName = scanner.next();
List <String> leaderList = new ArrayList<String>();
masterList.add(leaderList);
} else {
System.out.println("What is the leader" + i + "'s name?");
leaderName = scanner.next();
List <String> leaderList = new ArrayList<String>();
masterList.add(leaderList);
}
}
}
public void genMembers() {
System.out.println("Please enter the members on the following:");
for (int i = 1; i <= numMembers; i++) {
if (i == numMembers) {
System.out.println("What is the last member's name?");
memberName = scanner.next();
memberList.add(memberName);
} else {
System.out.println("What is the member" + i + "'s name?");
memberName = scanner.next();
memberList.add(memberName);
}
}
}
public void /*should return arraylist*/ brackets() {
double y = 1.0/numLeaders;
for (double j = 0.0; j <= 1.0; y++) {
//Generate Linked list with initial element of 0.0
//then 0.0 + y, then 0.0 + y + y ... till 1.0
}
}
public void assignMembers() {
System.out.println("Shuffling members..");
Collections.shuffle(memberList);
System.out.println("Assigning members to leaders now..");
int cellSize = memberList.size()/numLeaders;
for (int i = 0; i <= memberList.size(); i++) {
double x = Math.random();
double y = 1.0/numLeaders;
if (x <= y) {
masterList.get(0).add((String) memberList.get(i));
}
else if (y < x && x <= y + y) {
masterList.get(1).add((String) memberList.get(i));
}
else if (y < x && y + y < x && x <= y + y + y) {
masterList.get(2).add((String) memberList.get(i));
}
// assign given element's name from the big linkedList to the first leader's
// arrayList
}
}
public static void main(String[] args) {
Generator x = new Generator();
x.getNumLeader();
x.getNumMembers();
x.genLeaders();
x.genMembers();
System.out.println(x.memberList);
System.out.println(x.masterList);
System.out.println(x.masterList.get(0));
System.out.println(x.masterList.get(1));
System.out.println(x.masterList.get(2));
}
}
And I made lists within an arraylist, called masterList. I try to assign people in a list within that arraylist, in this manner: masterList.get(0).add((String) memberList.get(i)); Nothing's being added to the list within the arrayList.. what would be the 'correct' way to do this, and is there a way to pinpoint the list within the arraylist, other than 'masterList.get(0)'? Thanks in advance.
You are calling 4 methods, 2 to get numbers of leader and member, and another 2 to generate them. In your generateLeader method, you read name from console but never used it within this method. You are just adding emptylist to master list in this method. The other method generateMembers looks fine as you are adding this in the expected list. I dont see anywhere else that main method calls to populate the emptylist inside the masterlist you added in generateLeaders method.
Also, use nextln to read input, there are scenarios where the linebreak character will still be in buffer when you use just "next" and that linebreak will be read read as next input.

Incompatible type error with IntelliJ. The stock method takes an int and a double. What am I missing here?

See the purchase method below where the error occurs
public class StockMain {
public static void main (String[] args){
Scanner console = new Scanner (System.in);
// first stock
System.out.println("First stock symbol:");
String symbol1 = console.next();
Stock stock1 = new Stock (symbol1);
System.out.println("How much shares do you want to purchase?");
int units = console.nextInt();
System.out.println(" What is the price per share?");
double shareprice = console.nextDouble();
double profit1 = stock1.purchase(units,shareprice);
}
}
I just saw the error actually. The method returned nothing and I was assigning it to a variable.
public class Stock {
// This class represents a common stock on the market.
private String symbol;
private int totalShares;
private double totalCost;
// constructors begin here
// pre: Stock != null
public Stock (String theSymbol){
// initialise stock with no shares purchased
if (theSymbol == null) throw new NullPointerException();
symbol = theSymbol;
totalShares = 0;
totalCost = 0.0;
}
// methods begin here
public double getProfit(double currentPrice){
// return the total price of the stock.
if (currentPrice < 0 ) throw new IllegalArgumentException();
return totalShares * currentPrice - totalCost;
}
public void purchase (int shares, double pricePerShare){
// records the purchase units and prices of shares
if (pricePerShare < 0 || shares < 0) throw new IllegalArgumentException();
totalShares += shares;
totalCost += pricePerShare * shares;
}
public String getSymbol(){
return symbol;
}
}

Data sets with floating points

My main program will create a DataSet object, read in values and call the addValue instance method until it encounters a negative value. Then it will call the getAverage and getStandardDeviation methods and print out the return results. the average is 3.28
the Standard Deviation is 1.972815247
this is my code. I'm basically stuck right now.
import java.util.Scanner;
public class DataSet {
private double value;
private double count;
private double sum;
private double sumofSquares;
public void addValue(double value) {
while (value >= 0) {
count++;
sum += value;
sumofSquares += (value * value);
}
}
public double getAverage() {
return sum / count;
}
public double getStandardDeviation() {
return Math.sqrt(((count * sumofSquares) - (sum * sum)) / (count * (count - 1)));
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter Value");
double value = sc.nextDouble();
DataSet j1 = new DataSet();
j1.addValue(value);
System.out.println("The average of the value " + j1.getAverage());
System.out.println("The Standard Deviation of the value" + j1.getStandardDeviation());
}
}
There seems to be a lot wrong with this code. Firstly, your input code is not inside of a while loop, so you are not going to intake any new values. Secondly, your addValue function invokes an infinite loop upon entering a positive value, because the while loop will continue to run and add to your DataSet members.
I've refactored your code to make more sense, ask if you have any questions on any specific areas.
import java.util.Scanner;
public class DataSet {
private double value;
private double count;
private double sum;
private double sumofSquares;
public int addValue(double value) {
if(value >= 0) {
count++;
sum += value;
sumofSquares += (value * value);
return 0;
}else{
System.out.println("The average of the value " + this.getAverage());
System.out.println("The Standard Deviation of the value " + this.getStandardDeviation());
return -1;
}
}
public double getAverage() {
return sum / count;
}
public double getStandardDeviation() {
return Math.sqrt(((count * sumofSquares) - (sum * sum)) / (count * (count - 1)));
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter Values");
double value = 0;
DataSet j1 = new DataSet();
while(true){
value = sc.nextDouble();
if(j1.addValue(value) == 0){
//continue
}else{
return;
}
}
}
}

Simple Calculation in Java using Methods

I cannot find out where my mathematical error is. I just cannot see why I continue to receive no values back for my determineCableSrvs method.
private static Scanner input = new Scanner(System.in); //STORES CUSTOMER NAME STRING VALUE
public static void main(String[] args)
{//BEGIN main()
//Variables
int subscription = 0; //STORES SUBSCRIPTION INTEGER VALUE
int moviesOnDemand = 0; //STORES MOVIES ON DEMAND INTEGER VALUE
double cableSrvs = 0; //STORES TOTAL CABLE SERVICE DECIMAL VALUE
double totalMovieCharges = 0; //STORES TOTAL MOVIE CHARGES DECIMAL VALUE
double total = 0; //STORES TOTAL DECIMAL VALUE
char confirm = 'Y'; //LOOP CONTROL VARIABLE SET TO Y
Calendar dateTime = Calendar.getInstance(); //STORES THE DATE VALUE
String customerName = "";
while(Character.toUpperCase(confirm) == 'Y') //START OF WHILE LOOP AUTOMATICALLY ENTERS
{
String customer = setCustNm(customerName);
double cable = setCablePkg(subscription);
double type = determineCableSrv(subscription, cableSrvs);
int movies = setMoviePurchase(moviesOnDemand);
totalMovieCharges = movies * 7; //CALCULATING THE TOTAL MOVIE ON DEMAND CHARGE
total = totalMovieCharges + type; //CALCULATING THE OVERALL TOTAL
System.out.printf("%n%s %tD"
+ "\nCustomer: %S"
+ "%n%nCable Service: $%,21.2f"
+ "%nMovies-On-Demand-HD: %,20.2f"
+ "\n\nTOTAL DUE: $%,21.2f\n",
"SA CABLE CHARGES AS OF", dateTime, customer, type,
totalMovieCharges, total);
input.nextLine();
askNewSubscription(confirm);
printThankYou(confirm);
}
}
public static String setCustNm(String customerName)
{
// 1st prompt
System.out.printf("%n%n%nWELCOME TO SA CABLE %n");
System.out.printf("%nPlease enter your name: "); //PROMPTING USER TO ENTER NAME
customerName = input.nextLine(); //CAPTURES USERS NAME
return customerName;
}
public static int setCablePkg(int subscription)
{
do{
// 2nd Prompt DISPLAYING THE DIFFERENT PACKAGES AVAILABLE FOR SUBSCRIPTION
System.out.printf("%nSA CABLE - SUBSCRIPTION PACKAGES " +
"%n%n1. Basic: Local & major TV network channels %s" +
"%n2. Deluxe: Local, major TV, cable & 100 other channels %s" +
"%n3. Premium: Deluxe package plus HEB, on-demand & 300 other channels %s",
"$35.00", "75.00", "110.00") ;
System.out.printf("%n%nSelect your cable subscription package: ");
subscription = input.nextInt();//CAPTURING USER INPUT
}while (subscription < 1 || subscription > 3);
return subscription;
}
public static double determineCableSrv(int subscription, double cableSrvs)
{
if(subscription == 1) // IF STATEMENT TO IDENTIFY THE PRICE OF THE TOTAL CABLE SERVICE
{
cableSrvs = 35;
}
else if(subscription == 2)
{
cableSrvs = 75;
}
else if(subscription == 3)
{
cableSrvs = 110;
}
return cableSrvs;
}
public static int setMoviePurchase(int moviesOnDemand)
{
System.out.printf("%nSA CABLE - MOVIES " +
"%n%nEnter the number of Movies-On-Demand-HD purchases: ");
moviesOnDemand = input.nextInt();
return moviesOnDemand;
}
public static char askNewSubscription(char confirm)
{
System.out.printf("\nEnter 'Y' to continue with a new subscription or 'N' to exit: ");
confirm = input.nextLine().charAt(0);
return confirm;
}
public static char printThankYou(char confirm)
{
if(Character.toUpperCase(confirm) == 'Y')
{
confirm = 'Y';
}
if (Character.toUpperCase(confirm) != 'Y')
{
confirm = 'N';
System.out.printf("Thank you for being a valued SA Cable customer!");
System.exit(0);
}
return confirm;
}
I'm having trouble with this part:
public static double determineCableSrv(int subscription, double cableSrvs)
{
if(subscription == 1) // IF STATEMENT TO IDENTIFY THE PRICE OF THE TOTAL CABLE SERVICE
{
cableSrvs = 35;
}
else if(subscription == 2)
{
cableSrvs = 75;
}
else if(subscription == 3)
{
cableSrvs = 110;
}
return cableSrvs;
}
Here is how I'm calling the method:
double type = determineCableSrv(subscription, cableSrvs);
I cannot seem to get the return value. I need the value for:
total = totalMovieCharges + type; //CALCULATING THE OVERALL TOTAL
and this print out statement:
System.out.printf("%n%s %tD"
+ "\nCustomer: %S"
+ "%n%nCable Service: $%,21.2f"
+ "%nMovies-On-Demand-HD: %,20.2f"
+ "\n\nTOTAL DUE: $%,21.2f\n",
"SA CABLE CHARGES AS OF", dateTime, customer, type,
totalMovieCharges, total);
You set subscription equal to 0 and never change it before passing it in to the determineCableSrv method. You do the same with cableSrvs, so the return value from your method is going to be 0. The cableSrvs variable isn't read inside the method, so it probably shouldn't be in input parameter to begin with.

Java - Calling methods from other classes with calculated fields

So I've been looking at this piece of code all afternoon and I can't see the error(s). Here is what I'm supposed to do:
Create a Delivery class for a delivery service. The class contains fields to hold the following:
A delivery number that contains eight digits. The first four digits represent the year, and the last four digits represent the delivery number.
A code representing the delivery area. A local delivery is code 1, and a long distance delivery is code 2.
A weight, in pounds, of the item to be delivered.
The fee for the delivery, as follows:
Create a constructor for the Delivery class that accepts arguments for the year,
delivery number within the year, delivery distance code, and weight of the package. The
constructor determines the eight-digit delivery number and delivery fee. Also include a
method that displays every Delivery object field. Save the file as Delivery.java.
Next, create an application that prompts the user for data for a delivery. Keep
prompting the user for each of the following values until they are valid:
A four-digit year between 2001 and 2025 inclusive
A delivery number for the year between 1 and 9999 inclusive
A package weight between 0.10 pound and 100 pounds inclusive
A delivery distance code that is either 1 or 2
When all the data entries are valid, construct a Delivery object, and then display its
values. Save the file as CreateDelivery.java.
So here is my delivery Class
import javax.swing.*;
import java.util.*;
class Delivery
{
//variables
private int year;
private int deliveryNumber; //deliveryNo
private double weight;
private int distanceCode; //code
//constructor
//Delivery()
//{
// year = year;
// deliveryNumber = deliveryNumber;
// weight = weight;
// distanceCode = distanceCode;
//}
//get year
public int getYear()
{
return year;
}
//set year
public int setYear (int newYear)
{
year = newYear;
return year;
}
//get deliveryNumber
public int getDeliveryNumber()
{
return deliveryNumber;
}
//set deliveryNumber
public int setDeliveryNumber (int newDeliveryNumber)
{
deliveryNumber = newDeliveryNumber;
return deliveryNumber;
}
//get weight
public double getWeight()
{
return weight;
}
//set Weight
public double setWeight (double newWeight)
{
weight = newWeight;
return weight;
}
//get distanceCode
public int getDistanceCode()
{
return distanceCode;
}
//set distanceCode
public int setDistanceCode (int newDistanceCode)
{
distanceCode = newDistanceCode;
return distanceCode;
}
//calculate fee
public double displayFees(int distance, double w) //distance = c
{
double fees = 0;
if(distance == 1)
{
if(w < 5)
{
fees = 12;
}
else if((w < 20)&&(w > 5))
{
fees = 16.50;
}
else if(w > 20)
{
fees = 22;
}
}
else if(distance == 2)
{
if(w < 5)
{
fees = 35;
}
else if(w >= 5)
{
fees = 47.95;
}
}
return fees;
}
//display method
public void display(int year, int deliveryNumber, double weight, int distanceCode)
{
System.out.println("Year: " + year + '\n'
+ "Delivery Number: " + deliveryNumber + '\n'
+ "Weight of the package: " + weight + '\n'
+ "Delivery code: " + distanceCode);
}
}
And here is my CreateDelivery Class
import javax.swing.JOptionPane;
import java.util.Scanner;
public class CreateDelivery
{
public static void main(String []args)
{
Delivery delivery1 = new Delivery();
//scanner year
Scanner input = new Scanner(System.in);
System.out.print("Please enter the current year, format (yyyy) >>> ");
delivery1.setYear(input.nextInt());
//loop year
while((delivery1.getYear() <= 2000)||(delivery1.getYear() >= 2026))
{
System.out.println('\n'+ "Error, year should be in the range of (2010 - 2025). Please enter a valid option >> ");
delivery1.setYear(input.nextInt());
}
//scanner for delivery number
System.out.print('\n'+ "Please enter a delivery number: ");
delivery1.setDeliveryNumber(input.nextInt());
//loop for delivery number
while((delivery1.getDeliveryNumber() <= 0001)||(delivery1.getDeliveryNumber() >= 10000))
{
System.out.println("Error, the delivery number is a 4 digit number between 0001 and 9999, please enter a valid option >> ");
delivery1.setDeliveryNumber(input.nextInt());
}
//scanner for weight
System.out.print("Please enter the weight of the package (in pounds): ");
delivery1.setWeight(input.nextDouble());
//loop for weight
while((delivery1.getWeight() <= .09)||(delivery1.getWeight() >= 101))
{
System.out.println("Error, the minimum allowed weight is 0.10 pounds and the maximum is 100 pounds. Please enter a valid weight >> ");
delivery1.setWeight(input.nextDouble());
}
//scanner for delivery code
System.out.print("Please enter 1 for local or 2 for long distance deliveries >> ");
delivery1.setDistanceCode(input.nextInt());
//loop for delivery code
while((delivery1.getDistanceCode() == 1) && (delivery1.getDistanceCode() == 2))
{
System.out.println("Error, please enter a valid distance code (1 for local deliveries and 2 for long distance deliveries) >> ");
delivery1.setDistanceCode(input.nextInt());
}
//turn int to string
String n = Integer.toString(delivery1.getDeliveryNumber());
String y = Integer.toString(delivery1.getYear());
String trackingNumber = n + y;
System.out.println(delivery1.getDistanceCode() + " "
+ trackingNumber + " " + delivery1.getWeight() + " " + fees);
}
}
So I made the changes you guys suggested, but now I can't pull fees from the Delivery class. Any thoughts?
Delivery()
{
year = year;
deliveryNumber = deliveryNumber;
weight = weight;
distanceCode = distanceCode;
}
Replace it with something along the lines of:
Delivery(int year, int deliveryNumber, int weight, int distanceCode)
{
this.year = year;
this.deliveryNumber = deliveryNumber;
this.weight = weight;
this.distanceCode = distanceCode;
}
From there, I would avoid using the set methods. Instead, store all the values into respective fields as you load them from the System.in. Once you have all the fields, create the Delivery object.
I think you are missing () at the end of the methods such as getDeliveryNumber,getYear etc. in the while loop.
and you are also using undeclared variables at the end such as getDeliveryNumber,getYear etc.
or we can do that simply like Delivery class
public class Delivery {
private int year,deliveryNumber,distanceCode;
private double weight;
private double fees=0;
//delivery class constructor
public Delivery(int year,int deliveryNumber,int distanceCode,double weight)
{
this.year=year;
this.deliveryNumber=deliveryNumber;
this.distanceCode=distanceCode;
this.weight=weight;
}
//calculate delivery fee
public void displayFees(int distanceCode, double weight)
{
if(distanceCode == 1)
{
if(weight<5)
{
fees = 12;
}
else if((weight < 20)&&(weight >=5))
{
fees = 16.50;
}
else if(weight > 20)
{
fees = 22;
}
}
else if(distanceCode == 2)
{
if(weight <5)
{
fees = 35;
}
else if(weight >= 5)
{
fees = 47.95;
}
}
}
public double getFee()
{
return fees;
}
}
and CreateDelivery class:
public class CreateDelivery {
public static void main(String[] args) {
int year=(int)ReadValues.readValue("Year", 1999,2026);
int deliveryNumber=(int)ReadValues.readValue("Delivery Number (1 to 10000)", 0,10000);
int distanceCode=(int)ReadValues.readValue("DistanceCode (1 or 2)",0, 3);
double weight=ReadValues.readValue("weight",0, 20);
Delivery delivery=new Delivery(year, deliveryNumber, distanceCode, weight);
delivery.displayFees(distanceCode, weight);
double fee=delivery.getFee();
System.out.println("\n\n*****Delivery Fees Details*****\n\nTrackingNumber:"+year+deliveryNumber+"\nDistanceCode:"+distanceCode+"\nFee :"+fee);
}
}
and for reading values from user another class called ReadValue
import java.util.Scanner;
public class ReadValues {
public static double readValue(String prompt, int min, int max) {
Scanner scan = new Scanner(System.in);
double value;
System.out.print(prompt + " :");
while (true) {
value = scan.nextDouble();
if (value < min || value > max)
System.out.println("Enter value between " + min + " & " + max);
else
break;
}
return value;
}
}

Categories

Resources