I'm trying to compile my first major program. Unfortunately in getBestFare() I get "null" coming out all the time. And it shouldn't! I'm asking you guys for help what's wrong.
I rebuilt the entire getBestFare() method but unfortunately it keeps coming up with "null". The earlier code was a bit more messy. Now it's better, but it still doesn't work.
public class TransitCalculator {
public int numberOfDays;
public int transCount;
public TransitCalculator(int numberOfDays, int transCount) {
if(numberOfDays <= 30 && numberOfDays > 0 && transCount > 0){
this.numberOfDays = numberOfDays;
this.transCount = transCount;
} else {
System.out.println("Invalid data.");
}
}
String[] length = {"Pay-per-ride", "7-day", "30-day"};
double[] cost = {2.75, 33.00, 127.00};
public double unlimited7Price(){
int weekCount = numberOfDays/7;
if (numberOfDays%7>0){
weekCount+=1;
}
double weeksCost = weekCount * cost[1];
return weeksCost;
}
public double[] getRidePrices(){
double price1 = cost[0];
double price2 = ((cost[1]*unlimited7Price()) / (unlimited7Price() * 7));
double price3 = cost[2] / numberOfDays;
double[] getRide = {price1, price2, price3};
return getRide;
}
public String getBestFare(){
int num = 0;
for (int i = 0; i < getRidePrices().length; i++) {
if(getRidePrices()[i] < getRidePrices()[num]){
return "You should get the " + length[num] + " Unlimited option at " + getRidePrices()[num]/transCount + " per ride.";
}
}
return null;
}
public static void main(String[] args){
TransitCalculator one = new TransitCalculator(30, 30);
System.out.println(one.unlimited7Price());
System.out.println(one.getRidePrices()[2]);
System.out.println(one.getBestFare());
}
}
I am trying to set up my Java code to parse whether an element of my array attended either Disneyland or Universal studios. My array has 7 elements for 7 attendees. The attendees receive discounts specific to which park they attended, and I have created two for loops to represent the two parks.
How can I set up my code in the main method to determine which attendees went where?
public class Visitor
{
public static void main( String args[] )
{
double totalAttendeeCost = 0.0;
//Using 1 array
VisitorPackage[] attendee = new VisitorPackage[7];
attendee[0] = new VisitorPackage("Mickey", 'S', "weekday",
"Disneyland", 75.0);
attendee[1] = new VisitorPackage("Donald", 'C', "weekday",
"Disneyland", 75.0);
attendee[2] = new VisitorPackage("Minnie", 'E', "weekend",
"Disneyland", 75.0);
attendee[3] = new VisitorPackage("Goofie", 'E', "weekend",
"Disneyland", 75.0);
attendee[4] = new VisitorPackage("Harry", 'C', "weekend", "Universal
Studios", 60.0);
attendee[5] = new VisitorPackage("Hermoine", 'S', "weekend",
"Universal Studios", 60.0);
attendee[6] = new VisitorPackage("Ron", 'E', "weekday", "Universal
Studios", 60.0);
//This is where I am looking for help
//if attendee == disneyland
for(int i=0; i < attendee.length; i++)
{
{
attendee[i].applyDiscount(attendee[i], 5.0, 10.0);
attendee[i].applyWeekdayRate(attendee[i], 15.0);
attendee[i].printInfo(attendee[i]);
totalAttendeeCost += attendee[i].getTotalCost();
}
}
//else if attendee == universal
for(int i=0; i < attendee.length; i++)
{
attendee[i].applyDiscount(attendee[i], 10.0, 15.0);
attendee[i].applyWeekdayRate(attendee[i], 20.0);
attendee[i].printInfo(attendee[i]);
totalAttendeeCost += attendee[i].getTotalCost();
}
//System.out.println("Total: $" + totalCostDisney + "\n");
System.out.println("--------------");
System.out.printf("Total: $%.2f\n", totalAttendeeCost);
}
}
Here is the other class containing the methods:
public class VisitorPackage
{
private String visitorName;
private char visitorType;
private String visitDay;
private String destination;
private double totalCost;
public VisitorPackage()
{
visitorName ="N/A";
visitorType = '-';
visitDay = "-";
destination = "N/A";
totalCost = 0.0;
}
public VisitorPackage(String newVisitorName, char newVisitorType,
String newVisitDay, String newDestination, double newTotalCost)
{
visitorName = newVisitorName;
visitorType = newVisitorType;
visitDay = newVisitDay;
totalCost = newTotalCost;
destination = newDestination;
}
public String getDestinationPark(VisitorPackage arrayInstance)
{
if (arrayInstance.destination.equalsIgnoreCase("disneyland"))
return destination;
else
return destination;
}
public double getTotalCost()
{
return totalCost;
}
public void applyDiscount(VisitorPackage arrayInstance, double
childRate, double seniorRate)
{
if (arrayInstance.visitorType == 'C')
totalCost -= ((totalCost * childRate) / 100);
else if (arrayInstance.visitorType == 'S')
totalCost -= ((totalCost * seniorRate) / 100);
}
public void applyWeekdayRate(VisitorPackage arrayInstance, double
weekdayDiscount)
{
if (arrayInstance.visitDay.equalsIgnoreCase("weekday"))
totalCost -= weekdayDiscount;
}
public void printInfo(VisitorPackage arrayInstance)
{
System.out.print(arrayInstance.visitorName + " - ");
System.out.print(arrayInstance.destination + " - ");
System.out.print("$");
System.out.printf("%.2f", arrayInstance.totalCost);
if (arrayInstance.visitorType == 'E')
System.out.print(" ***** Discount cannot be applied to " +
arrayInstance.visitorName);
System.out.println();
}
}
Keep in mind, each element of your attendee array is a specific instance of VisitorPackage. So, utilize your Getter methods within the VisitorPackage Class, but first get rid of the parameter for that method and simplify it like this:
public String getDestinationPark() {
return this.destination;
}
Do the same for all your other methods within the VisitorPackage Class, get rid of the VisitorPackage arrayInstance parameter and any relation to it within your class methods, like this:
public void applyDiscount(double childRate, double seniorRate) {
if (visitorType == 'C') {
totalCost -= ((totalCost * childRate) / 100);
}
else if (visitorType == 'S')
totalCost -= ((totalCost * seniorRate) / 100);
}
public void applyWeekdayRate(double weekdayDiscount) {
if (visitDay.equalsIgnoreCase("weekday")) {
totalCost -= weekdayDiscount;
}
}
public void printInfo() {
System.out.print(visitorName + " - ");
System.out.print(destination + " - ");
System.out.print("$");
System.out.printf("%.2f", totalCost);
if (visitorType == 'E') {
System.out.print(" ***** Discount cannot be applied to " + visitorName);
}
System.out.println();
}
Because each element of the attendee array is an instance of the VisitorPackage Class you don't need to send that instance to your class methods. It already knows which instance you are referring to (Mickey, Donald, Ron, etc) when you supply the Index number. Since Minnie is at index 2 of the attendee array any calls to the VisitorPackage class like attendee[2].applyWeekdayRate(15.0) will only ever apply to Minnie.
Now, when you want to process the attendee's Array:
// iterate through each attendee and
// apply necessary discounts, etc.
for (int i = 0; i < attendee.length; i++) {
// Disneyland
if (attendee[i].getDestinationPark().equalsIgnoreCase("disneyland")) {
attendee[i].applyDiscount(5.0, 10.0);
attendee[i].applyWeekdayRate(15.0);
attendee[i].printInfo();
totalAttendeeCost += attendee[i].getTotalCost();
}
// Universal Studios
else if (attendee[i].getDestinationPark().equalsIgnoreCase("universal studios")) {
attendee[i].applyDiscount(10.0, 15.0);
attendee[i].applyWeekdayRate(20.0);
attendee[i].printInfo();
totalAttendeeCost += attendee[i].getTotalCost();
}
}
Or you could do it like this:
for (int i = 0; i < attendee.length; i++) {
String dest = attendee[i].getDestinationPark();
if (dest.equalsIgnoreCase("disneyland")) {
attendee[i].applyDiscount(5.0, 10.0);
attendee[i].applyWeekdayRate(15.0);
attendee[i].printInfo();
totalAttendeeCost += attendee[i].getTotalCost();
}
else if (dest.equalsIgnoreCase("universal studios")) {
attendee[i].applyDiscount(10.0, 15.0);
attendee[i].applyWeekdayRate(20.0);
attendee[i].printInfo();
totalAttendeeCost += attendee[i].getTotalCost();
}
}
Or you could do it like this:
for (int i = 0; i < attendee.length; i++) {
String dest = attendee[i].getDestinationPark();
switch (dest.toLowerCase()) {
case "disneyland":
attendee[i].applyDiscount(5.0, 10.0);
attendee[i].applyWeekdayRate(15.0);
attendee[i].printInfo();
totalAttendeeCost += attendee[i].getTotalCost();
break;
case "universal studios": // if the string has a space
case "universalstudios": // OR if the string has no space
attendee[i].applyDiscount(10.0, 15.0);
attendee[i].applyWeekdayRate(20.0);
attendee[i].printInfo();
totalAttendeeCost += attendee[i].getTotalCost();
break;
}
}
In addition to the code issues pointed out by DevilsHnd, I wanted to steer you in a different direction.
Using streams to get the reporting you were looking for, and
Instead of using strings to represent things like Destination, Visitor Type and Visit Day, using enums to represent these concepts can clean up your code quite a bit and make it very clear how the discounting scheme works.
I've refactored your code accordingly
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import static java.util.stream.Collectors.groupingBy;
import static java.util.stream.Collectors.summingDouble;
public class Visitor {
public enum VisitorType {
Child, Senior, Other
}
public enum VisitType {
Weekday,Weekend
}
// represents each Destination as well as all related discount rates.
public enum Destination {
Disneyland {
{
visitorDiscount.put(VisitorType.Child, 5.0);
visitorDiscount.put(VisitorType.Senior, 10.0);
visitTypeDiscount.put(VisitType.Weekday, 15.0);
}
}
, UniversalStudios {
{
visitorDiscount.put(VisitorType.Child, 10.0);
visitorDiscount.put(VisitorType.Senior, 15.0);
visitTypeDiscount.put(VisitType.Weekday, 20.0);
}
};
protected Map<VisitorType,Double> visitorDiscount= new HashMap();
protected Map<VisitType,Double> visitTypeDiscount= new HashMap();
public double getVisitorTypeDiscount(VisitorType visitorType) {
Double discount = visitorDiscount.get(visitorType);
return discount == null ? 0.0 : discount;
}
public double getVisitTypeDiscount(VisitType visitType) {
Double discount = visitTypeDiscount.get(visitType);
return discount == null ? 0.0 : discount;
}
};
public static class VisitorPackage {
private final String visitorName;
private final VisitorType visitorType;
private final VisitType visitDay;
private final Destination destination;
private final double totalCost;
public VisitorPackage(String newVisitorName, VisitorType newVisitorType,
VisitType newVisitDay, Destination newDestination, double newTotalCost) {
visitorName = newVisitorName;
visitorType = newVisitorType;
visitDay = newVisitDay;
totalCost = newTotalCost;
destination = newDestination;
}
public String getDestinationPark() {
return destination.toString();
}
public double getTotalCost() {
return totalCost;
}
public double getDiscountedCost() {
double visitorTypeDiscount = totalCost * destination.getVisitorTypeDiscount(visitorType)/100;
return totalCost - visitorTypeDiscount - destination.getVisitTypeDiscount(visitDay);
}
public Destination getDestination() { return destination; }
public void printInfo() {
System.out.print(visitorName + " - ");
System.out.print(destination + " - ");
System.out.printf("$%.2f -> ", getTotalCost());
System.out.print("$");
System.out.printf("%.2f", getDiscountedCost());
if (visitorType == VisitorType.Other) {
System.out.print(" ***** Discount cannot be applied to "
+ visitorName);
}
System.out.println();
}
}
public static void main(String args[]) {
double totalAttendeeCost = 0.0;
//Using 1 array
VisitorPackage[] attendee = new VisitorPackage[7];
attendee[0] = new VisitorPackage("Mickey", VisitorType.Senior, VisitType.Weekday,
Destination.Disneyland, 75.0);
attendee[1] = new VisitorPackage("Donald", VisitorType.Child, VisitType.Weekday,
Destination.Disneyland, 75.0);
attendee[2] = new VisitorPackage("Minnie", VisitorType.Other, VisitType.Weekend,
Destination.Disneyland, 75.0);
attendee[3] = new VisitorPackage("Goofie", VisitorType.Other, VisitType.Weekend,
Destination.Disneyland, 75.0);
attendee[4] = new VisitorPackage("Harry", VisitorType.Child, VisitType.Weekend, Destination.UniversalStudios, 60.0);
attendee[5] = new VisitorPackage("Hermoine", VisitorType.Senior, VisitType.Weekend,
Destination.UniversalStudios, 60.0);
attendee[6] = new VisitorPackage("Ron", VisitorType.Other, VisitType.Weekday, Destination.UniversalStudios, 60.0);
// Print a report grouped by Destination showing all VisitoerPackages and their discounted costs with subtotals
Arrays.stream(attendee)
.collect(groupingBy(VisitorPackage::getDestination))
.entrySet().stream()
.forEach(e->{
System.out.println("Summary for "+e.getKey());
e.getValue().stream().forEach(VisitorPackage::printInfo);
Double total = e.getValue().stream().collect(summingDouble(VisitorPackage::getDiscountedCost));
System.out.printf("Total Discounted Cost for %s = $%.2f\n",e.getKey(),total);
System.out.println("------------------------------------------------------------");
});
// Here's a way to reduce the dataset to map of sub-totals keyed by destination.
Map<Destination,Double> discountedCostByDest = Arrays.stream(attendee)
.collect(groupingBy(
VisitorPackage::getDestination,
summingDouble(VisitorPackage::getDiscountedCost)));
System.out.println(discountedCostByDest);
// compute and display the total cost.
Double totalDiscountedCost = Arrays.stream(attendee)
.collect(summingDouble(VisitorPackage::getDiscountedCost));
System.out.printf("Grand Total = $%.2f\n", totalDiscountedCost);
}
}
This code produces the following output:
Summary for UniversalStudios
Harry - UniversalStudios - $60.00 -> $54.00
Hermoine - UniversalStudios - $60.00 -> $51.00
Ron - UniversalStudios - $60.00 -> $40.00 ***** Discount cannot be applied to Ron
Total Discounted Cost for UniversalStudios = $145.00
------------------------------------------------------------
Summary for Disneyland
Mickey - Disneyland - $75.00 -> $52.50
Donald - Disneyland - $75.00 -> $56.25
Minnie - Disneyland - $75.00 -> $75.00 ***** Discount cannot be applied to Minnie
Goofie - Disneyland - $75.00 -> $75.00 ***** Discount cannot be applied to Goofie
Total Discounted Cost for Disneyland = $258.75
------------------------------------------------------------
{UniversalStudios=145.0, Disneyland=258.75}
Grand Total = $403.75
When compiling I get a "java.util.MissingFormatArgumentException: null (in java.util.Formater) I do not know why.
"Exception in thread "main" java.util.MissingFormatArgumentException: Format specifier 's'"
Please Help.
import java.lang.*;
import java.util.Random;
import java.util.Scanner;
import static java.lang.System.out;
public class DartSimV1
{
static double[] SiXX(int Money)
{
double[] VarXX;
VarXX = new double[Money];
int IBS;
IBS = 0;
if (IBS < VarXX.length) {
do {
VarXX[IBS] = Math.random();
IBS++;
} while (IBS < VarXX.length);
}
return VarXX;
}
public static double[] SiYY(int Money)
{
double[] VarYY;
VarYY = new double[Money];
int IBS;
IBS = 0;
while (true) {
if (false) {
break;
}
if (!(IBS < VarYY.length)) {
break;
}
VarYY[IBS]=Math.random();
IBS++;
}
return VarYY;
}
public static double WhatPie(double[] IBS,double[] YYCoord)
{
double [] VarXX;
VarXX = IBS;
double [] VarYY;
VarYY = YYCoord;
double Totals;
Totals = 0;
double Contacts;
Contacts = 0;
int IBO;
IBO = 0;
if (IBO < VarXX.length) {
if ((Math.pow(VarXX[IBO], 2) + Math.pow(VarYY[IBO], 2)) <= 1) {
Totals++;
Contacts++;
} else Totals++;
IBO++;
if (IBO < VarXX.length) {
do {
if ((Math.pow(VarXX[IBO], 2) + Math.pow(VarYY[IBO], 2)) <= 1) {
Totals++;
Contacts++;
} else {
Totals++;
}
IBO++;
} while (IBO < VarXX.length);
}
}
double PIE;
PIE = 4 *
(Contacts
/
Totals);
return PIE;
}
public static void Answers(int Done, double New)
{
double PIE;
PIE = New;
System.out.printf("Trial [" + Done +"]: PIE = %11.3f%s",PIE);
}
public static void PieA(double[] New, int Done)
{
double[] PIE;
PIE = New;
int trials;
trials = Done;
double Totals;
Totals = 0.0;
int i;
i = 0;
if (i < PIE.length) {
double IBS;
IBS = PIE[i];
Totals += IBS;
i++;
if (i < PIE.length) {
do {
IBS = PIE[i];
Totals += IBS;
i++;
} while (i < PIE.length);
}
}
double PieA;
PieA = Totals/trials;
System.out.printf("AVG for π = %11.3f%s",PieA);
}
public static void main(String[] args)
{
Scanner show;
show = new Scanner(System.in);
System.out.print("# per trials?: ");
int dPt;
dPt = show.nextInt();
System.out.print("Trial #'s?: ");
int nTri;
nTri = show.nextInt();
double[] PieA;
PieA = new double[nTri];
int IBS=0;
while (IBS<nTri) {
double [] VarXX;
VarXX = SiXX(dPt);
double [] VarYY;
VarYY = SiYY(dPt);
double PIE;
PIE = WhatPie(VarXX,VarYY);
PieA[IBS]=PIE;
Answers(IBS,PIE);
IBS++;
}
PieA(PieA,nTri);
}
}
System.out.printf("Trial [" + Done +"]: PIE = %11.3f%s",PIE); has 2 parameters: one float %11.3f and one string %s. You've only given it one value to print PIE. It needs two - a float and a string.
Also: The exception gives you the full details of the problem - including the line number. You should include that in your question to give people the best chance of answering.
It seems that 20 regiments were in a continuous process of formation. The first had 1000 men, the second had 950, the third 900, and so on down to the twentieth regiment, which garrisoned only 50. During each week, 100 men were added to each regiment, and at week's end, the largest regiment was sent off to the front.This lasted for a total of 20 weeks.
For this program I have already managed to print out the original number of men for each regiment. But I am having difficult adding 100 men to each regiment.The adding men must be a method in the army class. I am getting the regiment objects using a .txt file. All this files contains is the names of regiments numbered 1-20.
I currently have no errors my only problem is that I do not know how to add men to my regiment. I have to use the addMen method in the army class which I currently have blank.
public class Regiment {
private String name; //name of regiment
private int regNumber; //regiment number
private int men; // regiment men
public Regiment(int regNumber, String name, int men) {
this.name = name;
this.regNumber = regNumber;
this.men = men;
}
public String getName() {
return name;
}
public int getregNumber() {
return regNumber;
}
public int getMen() {
return men;
}
public int addMen2(int RegNumber) {
int men = 1050 - (regNumber * 50);
return men;
}
}
ArmyDataList:
class ArmyDataList {
public ArrayList<Regiment> list;
public ArmyDataList() {
list = new ArrayList<Regiment>();
}
public void AddToList(Regiment current) {
list.add(current);
}
public void RemoveFromList(Regiment current) {
list.remove(current);
}
public Regiment getLargest() {
if (list.isEmpty()) {
return null;
}
Regiment Reg1 = list.get(0);
for (int i = 1; i < list.size(); i++) {
Regiment current = list.get(i); // get next regiment
// is current regiment > largest
if (current.getMen() > Reg1.getMen()) {
Reg1 = current;
}
}
return Reg1;
}
public void addMen() {
}
public String toString() {
String out
= String.format("%28s%12s%n", "Regiments", " Men")
+ String.format("%12s%n", "Number")
+ String.format("%12s%16s%14s%n", "=======", "===============",
"=========");
for (int i = 0; i < list.size(); i++) {
Regiment regim = list.get(i);
int regNumber = regim.getregNumber();
String name = regim.getName();
int men = regim.addMen2(regNumber);
out = out + String.format("%12s", regNumber)
+ String.format("%16s", name)
+ String.format("%10s", men)
+ "\n";
}
return out + "\n";
}
}
RegimentTest:
public class RegimentTest {
public static void main(String[] args) throws IOException
{
ArmyDataList army = new ArmyDataList();
Scanner fileScan = new Scanner(new File("regiments.txt"));
System.out.println("Report Summary:\n");
while (fileScan.hasNext()) {
String line = fileScan.nextLine();
System.out.println(line);
Scanner in = new Scanner(line) ;
int regNumber = in.nextInt();
String name = in.next();
int men = 0 ; //men is set to 0 only because I havent add the men yet
Regiment adder = new Regiment(regNumber, name, men );
army.AddToList(adder) ;
}
System.out.println(army.toString());
}
Add a setMen(int numberOfMen) method to your Regiment class. Then in your addMen() method, you can do something like this:
public void addMen(){
for(Regiment r : list){ //iterate through the list of regiments
r.setMen(r.getMen() + 100); //add 100 men to each regiment
}
}
The setMen method would look like this:
public void setMen(int numberOfMen){
men = numberOfMen;
}
There is another issue with your toString method, where the regiment's addMen2 method is called - right now you're just printing the number, not initializing the number of men. In the constructor for your Regiment class, replace the line
this.men = men;
with
this.men = addMen2(regNumber);
Then in your toString method, replace
int men = regim.addMen2(regNumber);
with
int men = regim.getMen();
Here is what your main should look like:
public static void main(String[] args) throws IOException{
ArmyDataList army = new ArmyDataList();
Scanner fileScan = new Scanner(new File("regiments.txt"));
System.out.println("Report Summary:\n");
while (fileScan.hasNext()) {
String line = fileScan.nextLine();
System.out.println(line);
Scanner in = new Scanner(line);
int regNumber = in.nextInt();
String name = in.next();
int men = 0 ; //men is set to 0 only because I havent add the men yet
Regiment adder = new Regiment(regNumber, name, men );
army.AddToList(adder);
}
System.out.println(army.toString()); //print out the initial # of men
for(int i = 0; i < 20; i++)
army.addMen();
System.out.println(army.toString()); //print the final # of men
}
in Regiment get rid of method addMen2, and replace it with
public void addMen(int men) {
this.men +=men;
}
then in your army you could have method
public void addMen(int men) {
for(Regiment regiment : list){
regiment.addMen(men);
}
}
that will be simplest solution to add 100 men to each regiment,
other thing is, your toString is bit nasty, regiment should know how meny soldiers it ghas, you shouldnt need additional method to calculate it (reason why i recommend you to trash addMen2 method)
to initiate your Regiment, use constructor. You want to have regiments in sizes 1000, 1950, 1900 etc, do it when you are creating them
while (fileScan.hasNext()) {
String line = fileScan.nextLine();
System.out.println(line);
Scanner in = new Scanner(line) ;
int regNumber = in.nextInt();
String name = in.next();
int men = 1050 - (regNumber * 50);
Regiment adder = new Regiment(regNumber, name, men );
army.AddToList(adder) ;
}
This is a programming assignment I am working on. It takes a single string input that represents a sequence of transactions and prints total gain/loss in the end.
I have my code written and think it should do what I want...but doesn't. I don't get any kind of output after running the program with the specified input.
The input I'm using is:
buy 100 share(s) at $20 each;buy 20 share(s) at $24 each;buy 200
share(s) at $36 each;sell 150 share(s) at $30 each;buy 50 share(s) at
$25 each;sell 200 share(s) at $35 each;
import java.util.*;
import java.text.*;
public class Stocks {
private int shares;
private int price;
private int temp;
private static int total;
private int finalPrice;
private int finalShares;
private Queue<Stocks> StockList = new LinkedList<Stocks>();
private static NumberFormat nf = NumberFormat.getCurrencyInstance();
public Stocks()
{
shares = 0;
price = 0;
}
public Stocks(int shares, int price)
{
this.shares = shares;
this.price = price;
}
public int getShares()
{
return this.shares;
}
public int getPrice()
{
return this.price;
}
public void setShares(int shares)
{
this.shares = shares;
}
public void setPrice(int price)
{
this.price = price;
}
public void sell() {
int sharesToSell = this.getShares();
int priceToSell = this.getPrice();
while (!StockList.isEmpty()) {
int numShares = StockList.peek().getShares();
int sharePrice = StockList.peek().getPrice();
if (numShares < sharesToSell || numShares == sharesToSell) {
temp = sharesToSell - numShares; // remaining shares to sell
finalShares = sharesToSell - temp; // # shares selling at price
finalPrice = priceToSell - sharePrice; // shares sold at adjusted price
total += (finalPrice * finalShares); // Calculates total price
StockList.remove();
sharesToSell = temp; // Remaining shares needed to be sold # price
}
if (numShares > sharesToSell) {
temp = numShares - sharesToSell; // Remaining shares that were bought
finalPrice = priceToSell - sharePrice; // Shares sold at adjusted price
total += (finalPrice * sharesToSell); // adds to running total
StockList.peek().setShares(temp);
}
}
}
public void buy() {
int numShares = this.getShares();
int priceToBuy = this.getPrice();
Stocks newStock = new Stocks(numShares,priceToBuy);
StockList.add(newStock); // adds stock to list
int temptotal = (numShares * priceToBuy); // decreases running total
total += (-1 * temptotal);
}
public static int getTotal() { // gets total profit (or loss)
return total;
}
// *****MAIN METHOD*****
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
System.out.println("Enter transaction sequence:");
String input = scan.nextLine().trim();
String[] inputArray = new String[50];
String[] inputArray2 = new String[50];
int numShares, sharePrice;
inputArray = input.split(";");
for (String i : inputArray) {
if (i.toUpperCase().contains("BUY")) {
inputArray2 = i.split(" ");
inputArray2[4] = inputArray2[4].substring(1);
try {
numShares = Integer.parseInt(inputArray2[1]);
sharePrice = Integer.parseInt(inputArray2[4]);
Stocks newStock = new Stocks(numShares,sharePrice);
newStock.buy();
} catch (NumberFormatException e) {
System.out.println("Error");
return;
}
}
else if (i.toUpperCase().contains("SELL")) {
inputArray2 = input.split(" ");
inputArray2[4] = inputArray2[4].substring(1);
try {
numShares = Integer.parseInt(inputArray2[1]);
sharePrice = Integer.parseInt(inputArray2[4]);
Stocks newStock = new Stocks(numShares,sharePrice);
newStock.sell();
} catch (NumberFormatException e) {
System.out.println("Error");
return;
}
} else {
System.out.println("Error - input does not contain buy/sell");
}
} System.out.println(nf.format(getTotal()));
}
}
You can clean up your parsing a lot by taking a look at java.util.regex.Matcher and java.util.regex.Pattern. They will let you match input against regular expressions. In addition, you can place parens in the regex to extract certain parts. So in your example, you really only care about three things: the operation(buy or sell), the quantity, and the price.
Here's a small example
String sentence = "john programs 10 times a day";
// here's our regex - each set of parens is a "group"
Pattern pattern = Pattern.compile("([A-Za-z]+) programs ([0-9]+) times a day");
Matcher matcher = pattern.matcher(sentence);
String person = matcher.group(1); // here we get the first group
String number = Integers.parseInt(matcher.group(2)); // here we get the second group
System.out.println("Person: " + person + " Number: " + number);
Looks like the main method is returning immediately when it parses a BUY transaction. You probably intended to put the return statement inside the catch block.