How to set up if-else in Java to parse array elements - java

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

Related

Why does it display the value "null" if the conditions of the method are met?

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());
}
}

Calculation on return cashback

I am a student who has just started getting touched with coding. I was trying to code a cashback calculation, but I got the wrong output. The calculation is based on which category user chooses; petrol, groceries, ewallet, etc. Once I get the categories, the list will get the amount based on the categories and calculate with the bonus cash back and cash back on eligible spend. If the amount calculated is more than or equal to 15, it will return 15.
The cashback calculation code:
private void function1() {
double amountGet, cashback = 0;
for (int i = 0; i< dataList.size(); i++) {
if(dataList.get(i).getCategory() == "Petrol Spend") {
amountGet = dataList.get(i).getAmount();
cashback = amountGet * 0.08;
if(cashback > 15) {
cashback = 15.00;
}
} else if(dataList.get(i).getCategory() == "Groceries Spend") {
amountGet = dataList.get(i).getAmount();
cashback = (amountGet * 0.078) + (amountGet * 0.002);
if(cashback > 15) {
cashback = 15.00;
}
} else if(dataList.get(i).getCategory() == "eWallet Transaction") {
amountGet = dataList.get(i).getAmount();
cashback = (amountGet * 0.078) + (amountGet*0.002);
if(cashback > 15) {
cashback = 15.00;
}
} else if (dataList.get(i).getCategory() == "Other Eligible Spend") {
amountGet = dataList.get(i).getAmount();
cashback = amountGet * 0.002;
if (cashback > 15) {
cashback = 15.00;
}
}
list.add(cashback);
}
}
This button for invoking the calculation code:
calculateBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
calculateCashBack();
}
});
private void calculateCashBack() {
if (totalAmount >=2000) {
function1();
} else {
function2();
}
for (int i =0; i< list.size(); i++) {
Log.d(TAG, "Item with ID :" + dataList.get(i).getId() + "with the amount of : RM" + dataList.get(i).getAmount() + "get Cashback of : RM" + list.get(i));
}
}
This is my output:
I would very much appreciate any the help from the experts...
As #GhostCat said, you should use String.equals() to compare strings. Here is an example of a more optimize, and prettier, code
// Init static values here
private Map<String, Float> cashbacks; // HashMap linking Category to dedicated cashback
static {
cashbacks = new HashMap<>();
cashbacks.put("Petrol Spend", 0.08f);
cashbacks.put("Groceries Spend", 0.08f);
cashbacks.put("eWallet Transaction", 0.08f);
cashbacks.put("Other Eligible Spend", 0.002f);
}
/**
* Compute cashbacks for a list of data
* #param dataList List of data
* #return List of corresponding cashbacks
*/
private List<Float> function1(List<Data> dataList) {
List<Float> results = new ArrayList<>();
for (Data data : dataList) {
// Find the category in the map
Float cash = cashbacks.get(data.category());
if (cash == null) {
cash = 0f; // default value here if no category found
}
// compute the total amount and limit the result to 15
results.add(Math.min(data.getAmount() * cash, 15));
}
return results;
}
How to use it? Simple:
private void calculateCashBack() {
List<Float> cashbacks;
if (totalAmount >=2000) {
cashbacks = function1(dataList);
} else {
cashbacks = function2(dataList); // I suppose that this function has the same signature
}
for (int i =0; i< cashbacks.size(); i++) {
Log.d(TAG, "Item with ID :" + dataList.get(i).getId() + " with the amount of : RM " + dataList.get(i).getAmount() + " get Cashback of : RM " + cashbacks.get(i));
}
}

How do I print every object in an arraylist and correctly count their quantity?

I have a class which takes an arraylist of items determined by their name, price and quantity and is supposed to print each unique item and increase quantity accordingly if more than one of the same item are added to the arraylist.
I have 2 problems with my current code: Firstly, It only prints the last item in the arraylist. Secondly, it returns an incorrect quantity for the printed item.
package shop;
import java.text.DecimalFormat;
import java.util.ArrayList;
public class ShoppingCart {
static ArrayList<Product> cart;
public ShoppingCart() {
ShoppingCart.cart = new ArrayList<Product>();
}
#Override
public String toString() {
DecimalFormat format = new DecimalFormat ("#.00");
int quantity = 0;
double price = 0;
String name = null;
double total = 0;
for (Product p: cart) {
quantity = p.getQuantity();
price = p.getPrice();
name = p.getName();
total = p.getTotalPrice();
}
return quantity + " * GBP " + format.format(price) + " " + name + " = GBP " + format.format(total);
}
public void add(Product p) {
if(cart.size() > 0) {
for (int i = 0; i < cart.size(); i++) {
if(cart.get(i).getName().equals(p.getName())
&& cart.get(i).getPrice() == p.getPrice()) {
cart.get(i).setQuantity(cart.get(i).getQuantity() + p.getQuantity());
}else {
cart.add(p);
}
}
}else {
cart.add(p);
}
}
public static void main(String[] args) {
ShoppingCart newCart = new ShoppingCart();
Product apple, apples, milk, caulk, ice, snakes;
apple = new Product("Apples (4 pack)", 1.20, 1);
apples = new Product("Apples (4 pack)", 1.20, 2);
milk = new Product("Milk (1l)", 0.75, 1);
caulk = new Product("Caulk (1l)", 6.84, 1);
ice = new Product("Ice (1kg)", 4.30, 1);
snakes = new Product("Snake (5m)", 32.0, 1);
newCart.add(apple);
newCart.add(apple);
newCart.add(apple);
newCart.add(apple);
newCart.add(caulk);
newCart.add(milk);
System.out.println(newCart);
}
}
The output is
4 * GBP .75 Milk (1l) = GBP 3.00
I'm guessing something has gone wrong in my toString() and add() methods, but I can't tell what.
You need to implement Product.toString() as follow for example :
#Override
public String toString() {
DecimalFormat format = new DecimalFormat("#.00");
return String.format("%d * GBP %5s %15s= GBP %5s", quantity, format.format(price),
name, format.format(price * quantity));
}
And the ShoppingCart.toString() will use Product.toString() of each Product :
#Override
public String toString() {
double total = 0;
StringBuilder sb = new StringBuilder();
for (Product p : cart) {
sb.append(p.toString()).append("\n");
total += p.getTotalPrice();
}
sb.append(String.format("%s%33.2f", "Total :", total));
return sb.toString();
}
Finally you'll get :
8 * GBP 1,20 Apples (4 pack)= GBP 9,60
2 * GBP 6,84 Caulk (1l)= GBP 13,68
4 * GBP ,75 Milk (1l)= GBP 3,00
4 * GBP ,75 Milk (1l)= GBP 3,00
Total : 29,28
As now, when you set a new quantity it affects the initial object as it's referenced in the list, you need to add a copy of in the list, also change the loop : when you find the same product, change the quantity then return, and **only at the end of the loop* if you haven't find the product you'll add it, you need to wait to check all the existant products :
public void add(Product p) {
if (cart.size() > 0) {
for (Product product : cart) {
if (product.getName().equals(p.getName()) && product.getPrice() == p.getPrice()) {
product.setQuantity(product.getQuantity() + p.getQuantity());
return;
}
}
cart.add(new Product(p));
} else {
cart.add(new Product(p));
}
}
And in Product class, a copy constructor :
public Product(Product p) {
this.quantity = p.quantity;
this.price = p.price;
this.name = p.name;
}
Also, don't make the list static, each shoppingCart has its own list
private ArrayList<Product> cart;
public ShoppingCart() {
cart = new ArrayList<>();
}
In toString() method you have a for loop but you are just keeping last item data in the loop. you should correct it like this:
String name = "";
for (Product p: cart) {
quantity += p.getQuantity();
price += p.getPrice();
name += p.getName();
total += p.getTotalPrice();
}

Creating an object with a constructor

i am working on a project and am stuck and have been for awhile, i want to make two objects, one t2001 and the other t2009. I made the constructor for them being TaxFiling but i am still getting a red underline error saying cannot find symbol? Does anyone know what i am doing wrong.
package ProgrammingAssignment;
import java.util.Scanner;
/**
*
* #author Joe
*/
public class Tax {
public static final int SINGLE_FILER = 0;
public static final int MARRIED_JOINTLY_OR_QUALIFYING_WIDOW = 1;
public static final int MARRIED_SEPARATELY = 2;
public static final int HEAD_OF_HOUSEHOLD = 3;
private int filingStatus;
private int[][] brackets;
private double[] rates;
private double taxableIncome;
public Tax(int filingStatus, int[][] brackets, double[] rates, double taxableIncome) {
this.filingStatus = filingStatus;
this.brackets = brackets;
this.rates = rates;
this.taxableIncome = taxableIncome;
}
public double getTax() {
double tax;
if (taxableIncome <= brackets[filingStatus][0]) {
return Math.round(taxableIncome * rates[0]);
}
tax = brackets[filingStatus][0] * rates[0];
for (int i = 1; i < brackets[filingStatus].length; i++) {
if (taxableIncome > brackets[filingStatus][i]) {
tax += (brackets[filingStatus][i] - brackets[filingStatus][i - 1]) * rates[i];
} else {
return Math.round(tax + (taxableIncome - brackets[filingStatus][i - 1]) * rates[i]);
}
}
return Math.round(tax + (taxableIncome - brackets[filingStatus][4]) * rates[5]);
}
public void TaxFiling(int taxYear, int[][] brackets, double[] rates) {
int Year = taxYear;
int[][] bracket = brackets;
double[] rate = rates;
}
public static void main(String[] args) {
int taxYear;
int sIncome;
int eIncome;
int stepVal;
Scanner input = new Scanner(System.in);
System.out.println("Enter a tax year: ");
taxYear = input.nextInt();
if (taxYear != 2009 && taxYear != 2001) {
System.out.println("Please Enter a Valid Year!");
System.exit(1);
}
System.out.println("Enter the starting income value: ");
sIncome = input.nextInt();
System.out.println("Enter ending income value: ");
eIncome = input.nextInt();
if (eIncome < sIncome) {
System.out.println("Ending Income Cannot Be Less Then Starting");
System.exit(2);
}
System.out.println("Enter a step value: ");
stepVal = input.nextInt();
if (stepVal < 0) {
System.out.println("Please Enter a Positive Step Value!");
System.exit(3);
}
System.out.println(taxYear + " Tax Table");
System.out.println("Income range: " + sIncome + " to " + eIncome);
int[][] brackets2009 = new int[][]{
// stat 0 single
{8350, 33950, 82250, 171550, 372950},
// stat 1 Married Filing Jointly
{16700, 67900, 137050, 208850, 372950},
// stat 2 Married Filing Separately
{8350, 33950, 68525, 104425, 186475},
// stat 3 Head of Household
{11950, 45500, 117450, 190200, 372950}};
int[][] brackets2001 = new int[][]{
// stat 0 single
{27050, 65550, 136750, 297350},
// stat 1 married joint
{45200, 109250, 166500, 297350},
// stat 2 married separate
{22600, 54625, 83250, 148675},
// stat 3 head of household
{36250, 93650, 15150, 297350}
};
double[] rates2009 = new double[]{0.10, 0.15, 0.25, 0.28, 0.33, 0.35};
double[] rates2001 = new double[]{.15, .275, .305, .355, .391};
TaxFiling t2001 = new TaxFiling(2001, brackets2001, rates2001);
TaxFiling t2009 = new TaxFiling(2009, brackets2009, rates2009);
if (taxYear == 2001) {
DisplayTaxTable(t2001, sIncome, eIncome, stepVal);
} else if (taxYear == 2009) {
DisplayTaxTable(t2009, sIncome, eIncome, stepVal);
}
}
public static void displayTaxTable(Tax tObj, int incomeStart, int incomeEnd, int incomeStep) {
String s1 = "Taxable Income";
String s2 = "Single";
String s3 = "Married Joint";
String s4 = "Married Separate";
String s5 = "Head of house";
System.out.printf(
"%-20s%-12s%-4s%21s%16s\n", s1, s2, s3, s4, s5);
for (int i = 50000;
i <= 60000; i += 1000) {
System.out.printf("%4d%19.0f%16.0f%16.0f%20.0f\n", i,
new Tax(Tax.SINGLE_FILER, brackets2009, rates2009, i).getTax(),
new Tax(Tax.MARRIED_JOINTLY_OR_QUALIFYING_WIDOW, brackets2009, rates2009, i).getTax(),
new Tax(Tax.MARRIED_SEPARATELY, brackets2009, rates2009, i).getTax(),
new Tax(Tax.HEAD_OF_HOUSEHOLD, brackets2009, rates2009, i).getTax()
);
}
for (int i = 50000;
i <= 60000; i += 1000) {
System.out.printf("%4d%19.0f%16.0f%16.0f%20.0f\n", i,
new Tax(Tax.SINGLE_FILER, brackets2001, rates2001, i).getTax(),
new Tax(Tax.MARRIED_JOINTLY_OR_QUALIFYING_WIDOW, brackets2001, rates2001, i).getTax(),
new Tax(Tax.MARRIED_SEPARATELY, brackets2001, rates2001, i).getTax(),
new Tax(Tax.HEAD_OF_HOUSEHOLD, brackets2009, rates2001, i).getTax()
);
}
}
}
You are trying to declare a constructor for TaxFiling inside of your Tax class. TaxFiling needs it's own separate class file or needs to be declared in a private class inside of your Tax class.
TaxFiling is not a constructor, its a method inside the Tax class, you need to create a different class for Taxfiling and create a constructor like:
public class TaxFiling {
public TaxFiling(int taxYear, int[][] brackets, double[] rates) {
}
}
public Tax(int taxYear, int[][] brackets, double[] rates) {
int Year = taxYear;
int[][] bracket = brackets;
double[] rate = rates;
}
This is what i changed it to and it works but when i try and pass the object into displayTaxTable i get more errors.
public static void displayTaxTable(Tax tObj, int incomeStart, int incomeEnd, int stepVal) {
String s1 = "Taxable Income";
String s2 = "Single";
String s3 = "Married Joint";
String s4 = "Married Separate";
String s5 = "Head of house";
System.out.printf(
"%-20s%-12s%-4s%21s%16s\n", s1, s2, s3, s4, s5);
for (int i = incomeStart;
i <= incomeEnd; i += stepVal) {
System.out.printf("%4d%19.0f%16.0f%16.0f%20.0f\n", i,
new Tax(Tax.SINGLE_FILER, bracket, rate, i).getTax(),
new Tax(Tax.MARRIED_JOINTLY_OR_QUALIFYING_WIDOW, bracket, rate, i).getTax(),
new Tax(Tax.MARRIED_SEPARATELY, bracket, rate, i).getTax(),
new Tax(Tax.HEAD_OF_HOUSEHOLD, bracket, rate, i).getTax()
);
}
}
If you write "new TaxFiling(...)", it means you call a constructor. But in your code, TaxFiling is a method.
Three options:
1) Make a class TaxFiling with fields taxYear, brackets and double rates. Make a constructor:
public TaxFiling(int taxYear, int[][] brackets, double[] rates) {
//set taxYear, brackets, rates etc
}
2) Make method taxFiling (methods start with lowercase!) return a Tax object like so:
public Tax taxFiling(int taxYear, int[][] brackets, double[] rates) {
return new Tax(/* set your data here */);
}
3) Make TaxFiling a constructor in Tax class. But, all constructors MUST be named exactly like the class they are in, like so:
public Tax(int taxYear, int[][] brackets, double[] rates) {
//set taxYear, brackets, rates etc
}
Beware, in displayTaxTable method, you don't use the tObj that you pass. Make use of it! Use getters to get information from that object

Java code written but no expected output after running

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.

Categories