Java Ticket program with inheritance - java

I have a program with different types of tickets. I have the Ticket, AdvanceTicket, and a StudentAdvanceTicket. I am printing the price of the ticket $50, advance ticket both options $30 and $40), and both options for student advance tickets $15 and $20.
Both options with the condition being if daysAhead >= 10.
I'v spent hours trying to solve this, I need help.
Ticket.java
public class Ticket {
private int number;
public Ticket(int number) {
this.number = number;
}
public double getPrice() {
return 50.0;
}
public String toString() {
return "Ticket #" + this.number + ", Price: $" + this.getPrice();
}
}
TicketMain.java
public class TicketMain {
public static void main(String[] args) {
Ticket[] tickets = new Ticket[5];
tickets[0] = new WalkupTicket(1);
tickets[1] = new AdvanceTicket(2,12);
tickets[2] = new AdvanceTicket(3,8);
tickets[3] = new StudentAdvanceTicket(4,17);
tickets[4] = new StudentAdvanceTicket(5,7);
for (int i = 0; i<5; i++) {
System.out.println(tickets[i]);
//System.out.println(" ");
}
}
}
AdvanceTicket.java
public class AdvanceTicket extends Ticket {
private int daysAhead;
public AdvanceTicket(int number, int daysAhead) {
super(number);
this.daysAhead = daysAhead;
}
public double getPrice() {
if (daysAhead >= 10) {
return 30.00;
} else {
return 40.00;
}
}
public String toString() {
if (daysAhead >= 10) {
return super.toString() + " (" + this.daysAhead + " days ahead, you got a great deal!)";
} else {
return super.toString() + " (" + this.daysAhead + " days ahead, you could have saved a bit more)";
}
}
}
And finally the issue...
StudentAdvanceTicket.java
public class StudentAdvanceTicket extends AdvanceTicket {
public StudentAdvanceTicket(int number, int daysAhead) {
super(number, daysAhead);
super.price = super.getPrice() / 2;
}
public String toString() {
return super.toString() + " (ID Required) ";
}
}
This is my desired output.
Ticket #1, Price: $50.0
Ticket #2, Price: $30.0 (12 days ahead, you got a great deal!)
Ticket #3, Price: $40.0 (8 days ahead, you could have saved a bit more)
Ticket #4, Price: $15.0 (ID Required)
Ticket #5, Price: $20.0 (ID Required)

When you call getPrice() for a StudentAdvanceTicket, your program actually calls the implementation from AdvanceTicket, which will return $30 or $40.
Now when you call toString() for a StudentAdvanceTicket, it calls toString from the super, which is the one for AdvanceTicket, and that one calls the object's getPrice() method, which, again, just returns $30 or $40 and doesn't make use of the price member variable.
The correct solution is to override getPrice for the StudentAdvanceTicket class. In that method, you call super.getPrice() and then do the price manipulation with that.

In StudentAdvanceTicket there is a compile error because super.price cannot be resolved.

Related

How to make private hashmap in one class visible to other class [closed]

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 1 year ago.
Improve this question
So everything works great in my program, but I read that making variable not private in class is a big mistake, because it can make problems with others part of big program.
Well I tried making HashMap airplane and flight private but I get error that "The field Airplane.airplane is not visible",which is of course true.
But how do I then make it visible in interface class?
Thanks in advance, I'm still learning and I got to this part in course.
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner imeskanera = new Scanner(System.in);
Airplane airplane = new Airplane();
flight flight = new flight();
interface_aerodrom ui = new interface_aerodrom(imeskanera,airplane,flight);
ui.start();
}
}
/ Airplane class
import java.util.HashMap;
public class Airplane {
HashMap<String,Integer>airplane;
private String id;
private int capacity;
public Airplane() {
this.airplane = new HashMap<String,Integer>();
}
public void add(String id, int capacity) {
this.id = id;
this.capacity = capacity;
this.airplane.put(id, capacity);
}
public String id() {
return this.id;
}
public int capacity() {
return this.capacity;
}
public String airplaneinfo() {
return this.id + "( " + this.capacity + " )";
}
}
/interface class
import java.util.Scanner;
public class interface_aerodrom {
private Scanner imeskanera;
private Airplane airplane;
private flight flight;
public interface_aerodrom(Scanner scanner, Airplane airplane,flight flight) {
this.imeskanera = scanner;
this.airplane = airplane;
this.flight = flight;
}
public void start() {
System.out.println("Airport panel\r\n"
+ "--------------------");
System.out.println();
while(true) {
System.out.println("Choose operation:\r\n"
+ "[1] Add airplane\r\n"
+ "[2] Add flight\r\n"
+ "[x] Exit");
String input = this.imeskanera.nextLine();
input = input.toLowerCase();
input = input.trim();
if(input.equals("x")) {
flight_service();
break;
}
else if(input.equals("1")) {
addairplane();
}
else if(input.equals("2")){
addflight();
}
}
}
public void flight_service() {
System.out.println("Flight service\r\n"
+ "------------");
while(true) {
System.out.println("Choose operation:\r\n"
+ "[1] Print planes\r\n"
+ "[2] Print flights\r\n"
+ "[3] Print plane info\r\n"
+ "[x] Quit");
String input = this.imeskanera.nextLine();
input = input.toLowerCase();
input = input.trim();
if(input.equals("quit")){
break;
}
else if(input.equals("1")) {
for(String name : this.airplane.airplane.keySet()) {
int numberofseats = this.airplane.airplane.get(name);
String list = name + "( " + numberofseats + " )";
System.out.println(list);
}
}
else if(input.equals("2")){
for(String name : this.flight.flight.keySet()) {
String value = this.flight.flight.get(name);
String list = name + value;
System.out.println(list);
}
}
else if(input.equals("3")) {
System.out.println("Give plane ID: ");
String planeid = this.imeskanera.nextLine();
if(airplanecontains(planeid)) {
int numberofseats = this.airplane.airplane.get(planeid);
System.out.println(planeid + "( " + numberofseats + " )" );
} else {
System.out.println("That plane is not in our database");
}
}
}
}
public void addairplane() {
System.out.println("Give plane ID: ");
String ID = this.imeskanera.nextLine();
System.out.println("Give plane capacity: ");
int capacity = Integer.parseInt(this.imeskanera.nextLine());
this.airplane.add(ID, capacity);
}
public boolean airplanecontains(String ID) {
if(this.airplane.airplane.containsKey(ID)) {
return true;
}else {
return false;
}
}
public void addflight() {
System.out.println("Give plane ID: ");
String ID = this.imeskanera.nextLine();
if(airplanecontains(ID)) {
System.out.println("Give departure airport code: ");
String departure = this.imeskanera.nextLine();
System.out.println("Give destination airport code: ");
String destination = this.imeskanera.nextLine();
int seats = this.airplane.airplane.get(ID);
this.flight.flight.put(ID + " ( " + seats + " ) ",departure + "-" + destination);
}
else {
System.out.println("This plane is not in our database");
}
}
}
/ flight class
import java.util.HashMap;
public class flight {
HashMap<String,String>flight;
public flight() {
this.flight = new HashMap<String,String>();
}
public void add(String departure, String destination) {
this.flight.put(departure, destination);
}
}
Making a field private does not necessarily mean you can't share it. You can use a getter to return the HashMap.
private Map<String,Integer>airplane = new HashMap<>();
public Map<String,Integer> getAirPlaneMap() {
return airplane;
}
The reason being is that this hides implementation details and allows for future changes without affecting users of the class. Users don't need to know where the map comes from within your class. You could have retrieved it from some where yourself and the user wouldn't know.
You may also want to ensure a user can't change it. So you could do the following:
public Map<String,Integer> getAirPlaneMap() {
return Collections.unModifiableMap(airplane);
}
The above will prevent the user from adding or deleting map elements. But it won't prevent them from changing a retrieved object from the map unless that object is also immutable.
In general, setter and getters are the best way to allow users to set and retrieve values. And it is usually a good idea to make defensive copies of mutable items that they are retrieving to ensure that the retrieved values are consistent for all users during execution of the program.

Displaying a final price as currency format and reading from file in java

I'm nearly finished with a program I've been writing for quite some time for a school final assignment. It's 99% complete, but I'd like to add a couple things to make it as perfect as possible and need help.
I'd like to display the final price of an order in currency format, but have only figured out a way to format as currency if it's in my tostring method.
There's also bonus points to be had with this if I create a method that creates an order from a file. (ex: orders 1 Reece's Pieces, 6 sugar cookies, 1 chocolate chip cookie, and 1 scoop of caramel ice cream).
Here's my code. Any help is appreciated.
package dessertshop;
import java.text.NumberFormat;
import java.util.Scanner;
abstract class DessertItem
{
protected String name;
public DessertItem()
{
this.name = "";
}
public DessertItem( String name )
{
this.name = name;
}
public final String getName()
{
return name;
}
public abstract double getCost(int number);
}
class Candy extends DessertItem
{
private double pricePerPound;
public Candy( String name, double unitPrice )
{
super( name );
this.pricePerPound = unitPrice;
}
#Override
public double getCost(int amount)
{
return( amount * pricePerPound );
}
public String toString()
{
NumberFormat formatter = NumberFormat.getCurrencyInstance();
return( "Candy\t" + name + "\t # " + formatter.format( this.pricePerPound ) + " per pound");
}
}
class Cookie extends DessertItem
{
private double pricePerDozen;
public Cookie(String name, double pricePerDozen)
{
super(name);
this.pricePerDozen=pricePerDozen;
}
#Override
public double getCost(int amount)
{
return(amount * pricePerDozen)/12;
}
public String toString()
{
NumberFormat formatter = NumberFormat.getCurrencyInstance();
return( "Cookie\t" + name + "\t # " + formatter.format( this.pricePerDozen) + " per dozen");
}
}
class IceCream extends DessertItem
{
private double cost;
public IceCream(String name, double cost)
{
super(name);
this.cost=cost;
}
#Override
public double getCost(int amount)
{
return(amount * cost);
}
public String toString()
{
NumberFormat formatter = NumberFormat.getCurrencyInstance();
return( "Ice Cream\t" + name + "\t # " + formatter.format( this.cost ) + " per scoop");
}
}
public class DessertShop
{
private String name = "";
private DessertItem[] menu;
private int numberOfItems = 0;
public DessertShop(String name)
{
this.name = name;
menu = new DessertItem[200];
}
public DessertShop()
{
menu = new DessertItem[200];
}
public void addToMenu(DessertItem item)
{
menu[numberOfItems++] = item;
}
public void printMenu()
{
System.out.println(this.toString());
for (int i = 0; i < numberOfItems; i++)
{
System.out.print((i + 1) + ": " + menu[i].toString());
System.out.println("");
}
}
public double createNewOrder()
{
double totalCost = 0;
Scanner input = new Scanner(System.in);
while (true)
{
this.printMenu();
System.out.print("What would you like to purchase? (0 to checkout) > ");
int choice = input.nextInt();
if (choice == 0)
{
break;
}
System.out.print("How many (lbs. or amount) > ");
int amount = input.nextInt();
totalCost += menu[(choice - 1)].getCost(amount);
}
input.close();
return totalCost;
}
public String toString()
{
return ("Welcome to " + name);
}
public static void main( String[] args )
{
DessertShop shop01 = new DessertShop("Chuck D's Dessert Depot");
Candy candy01 = new Candy("Reece's Pieces", 3.99);
Candy candy02 = new Candy("Chocolate Covered Raisins", 4.99);
Cookie cookie01 = new Cookie("Peanut Butter", 5.99);
Cookie cookie02 = new Cookie("Chocolate Chip", 4.99);
Cookie cookie03 = new Cookie("Sugar", 4.50);
IceCream icecream01 = new IceCream("Cookie Dough", 3.00);
IceCream icecream02 = new IceCream("Vanilla", 2.00);
IceCream icecream03 = new IceCream("Caramel", 3.50);
IceCream icecream04 = new IceCream("Rocky Road", 2.99);
IceCream icecream05 = new IceCream("Mint Chocolate Chip", 3.99);
shop01.addToMenu(candy01);
shop01.addToMenu(candy02);
shop01.addToMenu(cookie01);
shop01.addToMenu(cookie02);
shop01.addToMenu(cookie03);
shop01.addToMenu(icecream01);
shop01.addToMenu(icecream02);
shop01.addToMenu(icecream03);
shop01.addToMenu(icecream04);
shop01.addToMenu(icecream05);
double frankOrder = shop01.createNewOrder();
System.out.println(frankOrder);
}
}
Depending on what you seek, you can format your price at your last line of code:
System.out.println(frankOrder)
have a look: here.
About the other question, reading in from file, I suggest you have a look at csv files: here and how to read them:here
If you don't want to hassle too much, you can get decent result with printf:
System.out.printf("Price is: €%,d", 12342353563623L);
Output is: Price is: €12,342,353,563,623
Formatter on "," flag:
The result will include locale-specific grouping separators

Java Overriding method issues

I am working on an assignment "Dessert Shoppe" and basically what I need to do is to create DessertItem subclasses Candy, Cookie, IceCream, Sundae and Checkout. I am also provided with DessertItem class & DessertShoppe and I am not allowed to modify them.
While I have created all these subclasses, when I run it on my TestCheckout.java , it will not work but rather display getName() in Sundae cannot override getName() in DessertItem.
public final String getName(){
^
overriden method is final.
I will provide you guys all the classes that I have made now.
public class DessertShoppe {
public final static double TAX_RATE = 6.5; // 6.5%
public final static String STORE_NAME = "M & M Dessert Shoppe";
public final static int MAX_ITEM_NAME_SIZE = 25;
public final static int COST_WIDTH = 6;
public static String cents2dollarsAndCents(int cents) {
String s = "";
if (cents < 0) {
s += "-";
cents *= -1;
}
int dollars = cents/100;
cents = cents % 100;
if (dollars > 0)
s += dollars;
s +=".";
if (cents < 10)
s += "0";
s += cents;
return s;
}
}
public abstract class DessertItem {
protected String name;
public DessertItem() {
this("");
}
public DessertItem(String name) {
if (name.length() <= DessertShoppe.MAX_ITEM_NAME_SIZE)
this.name = name;
else
this.name = name.substring(0,DessertShoppe.MAX_ITEM_NAME_SIZE);
}
public final String getName() {
return name;
}
public abstract int getCost();
}
public class Cookie extends DessertItem{
protected double number;
protected double pricePerDoze;
public Cookie(String _n, double _ppd, int _number){
super(_n);
pricePerDoze = _ppd;
number = _number;
}
public int getCost(){
return (int)Math.round(number / 12 * pricePerDoze);
}
}
public class Candy extends DessertItem{
protected double weight;
protected double pricePerPound;
public Candy(String _n, double _ppp, int _w){
//using parent's constructor with name while storing its own properties
super(_n);
pricePerPound = _ppp;
weight = _w;
}
public int getCost(){
return (int)Math.round(weight * pricePerPound);
}
}
public class IceCream extends DessertItem{
protected int cost;
public IceCream(String _n, int _cost){
super(_n);
cost = _cost;
}
public int getCost(){
return cost;
}
}
public class Sundae extends IceCream{
protected String topName;
protected int topCost;
public Sundae(String _n0, int _cost0, String _n1, int _cost1){
//put the icecream name in icecream while putting top name and cost in a separate property
super(_n0, _cost0);
topName = _n1;
topCost = _cost1;
}
public final String getName(){
//return both the icecream name and the topping name
return name + " " + topName;
}
public int getCost(){
//return the sum of the icecream and the topping
return cost + topCost;
}
}
public class Checkout{
protected int size;
protected DessertItem[] dessertItems;
protected int amount;
protected int sum;
protected final double taxRate;
Checkout(){
size = 100;
dessertItems = new DessertItem[size];
amount = 0;
sum = 0;
taxRate = DessertShoppe.TAX_RATE;
}
public void enterItem(DessertItem d){
dessertItems[amount] = d;
amount ++;
}
public int numberOfItems(){
return amount;
}
public int totalCost(){
//make sum into zero, and calculate price from every item
sum = 0;
for(int i = 0; i < amount; i ++){
sum += dessertItems[i].getCost();
}
return sum;
}
public int totalTax(){
//use the totalCost method
return (int)(Math.round(this.totalCost() * taxRate / 100));
}
public void clear(){
//clear the array
for(DessertItem d : dessertItems){
d = null;
}
amount = 0;
sum = 0;
}
public String toString(){
String result = "Thank You! \n";
result += DessertShoppe.STORE_NAME + "\n";
result += "Purchased: ";
String totalPay = DessertShoppe.cents2dollarsAndCents( totalCost()+totalTax() );
if(totalPay.length() > DessertShoppe.COST_WIDTH){
totalPay = totalPay.substring(0, DessertShoppe.COST_WIDTH);
}
result += "$" + totalPay;
return result;
}
}
public class TestCheckout {
public static void main(String[] args) {
Checkout checkout = new Checkout();
checkout.enterItem(new Candy("Peanut Butter Fudge", 2.25, 399));
checkout.enterItem(new IceCream("Vanilla Ice Cream",105));
checkout.enterItem(new Sundae("Choc. Chip Ice Cream",145, "Hot Fudge", 50));
checkout.enterItem(new Cookie("Oatmeal Raisin Cookies", 4, 399));
System.out.println("\nNumber of items: " + checkout.numberOfItems() + "\n");
System.out.println("\nTotal cost: " + checkout.totalCost() + "\n");
System.out.println("\nTotal tax: " + checkout.totalTax() + "\n");
System.out.println("\nCost + Tax: " + (checkout.totalCost() + checkout.totalTax()) + "\n");
System.out.println(checkout);
checkout.clear();
checkout.enterItem(new IceCream("Strawberry Ice Cream",145));
checkout.enterItem(new Sundae("Vanilla Ice Cream",105, "Caramel", 50));
checkout.enterItem(new Candy("Gummy Worms", 1.33, 89));
checkout.enterItem(new Cookie("Chocolate Chip Cookies", 4, 399));
checkout.enterItem(new Candy("Salt Water Taffy", 1.5, 209));
checkout.enterItem(new Candy("Candy Corn",3.0, 109));
System.out.println("\nNumber of items: " + checkout.numberOfItems() + "\n");
System.out.println("\nTotal cost: " + checkout.totalCost() + "\n");
System.out.println("\nTotal tax: " + checkout.totalTax() + "\n");
System.out.println("\nCost + Tax: " + (checkout.totalCost() + checkout.totalTax()) + "\n");
System.out.println(checkout);
}
}
The expected output should be:
Number of items: 4
Total cost: 1331
Total tax: 87
Cost + Tax: 1418
M & M Dessert Shoppe
--------------------
2.25 lbs. # 3.99 /lb.
Peanut Butter Fudge 8.98
Vanilla Ice Cream 1.05
Hot Fudge Sundae with
Choc. Chip Ice Cream 1.95
4 # 3.99 /dz.
Oatmeal Raisin Cookies 1.33
Tax .87
Total Cost 14.18
Number of items: 6
When a method is marked as final, it means that it cannot be overridden in a subclass.
Therefore, you need to use the getName() method as it stands, and figure out how to get the appropriate value into the name variable.
Luckily, there's a constructor in IceCream that does that, so all you need to do is pass into the constructor what you want getName() to return (and what you want getCost() to return):
public Sundae(String _n0, int _cost0, String _n1, int _cost1){
super(_n1 + " Sundae with\n" + _n0, _cost0 + _cost1);
}
This way, your Sundae class doesn't need a getName() or a getCost() method.
As stated in other answers, the final modifier means that the method cannot be overridden by any of its subclasses.
There are two ways around this:
The first is to pass the arguments into the Sundae constructor as shown by Jason:
super(_n0 + " " + _n1, _cost0 + _cost1);
The second would be to utilize the fact that Sundae is a subclass of IceCream, which is a subclass of DessertItem. The name field is protected, meaning that you could directly access the field from the constructor.
Keep in mind, that with the second option, you will need to explicitly check to make sure that the name you provide is shorter than DessertShoppe.MAX_ITEM_NAME_SIZE to keep in line with that standard length.
The simpler and probably intended solution would be the first one, though both are valid.

Learning Java, troubleshooting an assignment [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 7 years ago.
SO I have an assignment for one of my classes to create an Insurance Calculator that takes in some input for ones age, level of education, marriage status, and employment status and uses this to come up with an insurance payment. The default payment is set to 100 and if an individual is younger than 22 or older than 70, the insurance is increased by 25%. If the individual has a Bachelors, the cost is reduced by 10% (20% for masters), and if the individual is married it is further decreased by 20%. If their employment status is student, cost increases 10%, but if they are unemployed it decreases 5%. I have a huge block of code and Ive been running through it for the last few days and I seem to be stuck on my conditionals. Currently running in two classes, one for the Individual.Class and one for the user inputs.
Individual.java:
public class Individual {
private int age;
private String ed_stat;
private String mar_stat;
private String emp_stat;
private double default_Payment = 100;
public Individual(int suns, String edu, String mar, String employ, double payments) {
this.age = suns;
this.ed_stat = edu;
this.mar_stat = mar;
this.emp_stat = employ;
this.defaultPayment = payments;
}
public int getAge() {
return this.age;
}
public String getEdu() {
return this.ed_stat;
}
public String getMar() {
return this.mar_stat;
}
public String getEmploy() {
return this.emp_stat;
}
public double getPay(){
if (22 < age > 70) {
default_Payment = default_Payment + (default_Payment * .25);
}
if (ed_stat == "Bachelor's") {
default_Payment = default_Payment - (default_Payment * .10);
}
if (ed_stat == "Master's") {
default_Payment = default_Payment - (default_Payment * .20);
}
if (mar_stat == "yes") {
default_Payment = default_Payment - (default_Payment * .20);
}
if (emp_stat == "Student") {
default_Payment = default_Payment + (default_Payment * .10);
}
if (emp_stat == "Unemployed") {
default_Payment = default_Payment - (default_Payment * .05);
}
return this.default_Payment;
}
public void setAge(int suns) {
this.age = suns;
}
public void setEdu(String edu) {
this.ed_stat = edu;
}
public void setMar(String mar) {
this.mar_stat = mar;
}
public void setEmploy(String employ) {
this.emp_stat = employ;
}
public void setPayment(double payments) {
this.default_Payment = payments;
}
public String toString() {
return String("Age: " + age() + ", Education : " + ed_stat + ", Marital Status: " + mar_stat + ", Employment Status: " + emp_stat + ", Payment: " + default_Payment);
}
}
And the InsuranceCalculator.java
import java.util.Scanner;
public class InsuranceCalculator {
public static void main(String[] args) {
double insurance = 100;
Scanner scan = new Scanner(System.in);
System.out.println("Please enter your age: ");
int years = scan.nextInt();
System.out.println("Please enter your education level as High School, Bachelor's, or Master's");
String edu = scan.next();
System.out.println("Are you married? Yes or No");
String mar = scan.next();
System.out.println("Please indicate your employment status as Unemployed, Student, or Employed");
String employ = scan.next();
Individual me = new Individual(years, edu, mar, employ, insurance);
System.out.println(me.toString());
}
Note that I have errors in the Individual.java and I can't tell how the Calculator class will run once I fix the Individual.java.
Any help is greatly appreciated, I will be working on my own as well and will update as I solve
Rather than comparing Strings with the '==' operator, you want to use the .equals() method. For example:
if(ed_stat.equals("Bachelor's")){

My program is printing only the last input from the ArrayList

I have another small class containing the main method that display the
invoice, but the toString method here is only displaying the last item
entered, not the three itemnames,quantities, prices and totalPrice.
I have doubts about addItemLine and toString.
Can someone see what I am missing here?
I was enable to past the lineItem class code.
import java.util.ArrayList;
import java.util.Scanner;
public class Transaction {
private ArrayList<lineItem> lineItems;
private int customerID;
private String customerName;
public Transaction (int customerID, String customerName){
this.customerID= customerID;
this.customerName= customerName;
this.lineItems= new ArrayList<>();
}
public int getcustomerID(){
return customerID;
}
public void setcustomerID(int customerID){
this.customerID = customerID;
}
public String getcustomerName(){
return customerName;
}
public void setcustomerName(String customerName){
this.customerName = customerName;
}
public ArrayList addItemLine(lineItem line){
Scanner mykey=new Scanner(System.in);
for (int i=0; i<2;i++){
String k= line.getItemName();
int m= line.getQuantity();
double d= line.getPrice();
System.out.println("enter item name:");
k = mykey.next();
line.setItemName(k);
System.out.println("enter quantity:");
m= mykey.nextInt();
line.setQuantity(m);
System.out.println("enter unit price:");
d= mykey.nextDouble();
line.setPrice(d);
line.getItemName(); line.getQuantity(); line.getPrice();
lineItems.add(new lineItem(k,m,d));
}
return this.lineItems;
}
public void updateItem(String item, int quant, double pri){
lineItem l= new lineItem(item, quant, pri);
int m=0;
m= l.getQuantity();
m=m+quant;
double tot=0;
}
public double getTotalPrice(){
double totalPrice = 0;
for (int i =0;i<2; i++){
lineItem item = lineItems.get(i);
totalPrice = totalPrice + item.getTotalPrice();
}
return totalPrice;
}
public String getLineItem( String s, int d, double k){
lineItem o= new lineItem(s,d,k);
for (int i =0;i<2; i++){
if (!s.equals(o.getItemName()))
System.out.println("item not found");
else
s= (o.getItemName() + o.getQuantity() + o.getPrice());
}
return s;
}
public String toString(lineItem lin) {
String a="", b="";
a=("Customer ID:" + this.getcustomerID() + "\n" + "Customer Name: " +
this.getcustomerName());
for (int i=0; i<2;i++){
b= ("\n\n" + lin.getItemName() + "\t" + "Qty" + lin.getQuantity() + "
"
+ "#" + lin.getPrice() + " "+ "\t" + "$" + lin.getTotalPrice());
}
return a + b;
}
TransactionTesting:
import java.util.Scanner;
public class TransactionTesting {
public static void main(String args[]) {
String m=""; int g=0; double r=0; int id=0; String name="";
Scanner mykey= new Scanner(System.in);
System.out.println("enter customer name:");
name= mykey.nextLine();
System.out.println("enter customer ID:");
id=mykey.nextInt();
Transaction mytrans= new Transaction(id, name);
lineItem line= new lineItem(m,g,r);
mytrans.addItemLine(line);
System.out.println(mytrans.toString(line));
}
}
Change your toString() method like this:
public String toString() {
String a="", b="";
a=("Customer ID:" + this.getcustomerID() + "\n" + "Customer Name: " +
this.getcustomerName());
for (lineItem item : this.lineItems)
b += ("\n\n" + item.getItemName() + "\t" + "Qty" + item.getQuantity() + " "
+ "#" + item.getPrice() + " "+ "\t" + "$" + item.getPrice());
return a + b;
}
and from your test class call this method as the following:
System.out.println(mytrans.toString());
You don't need any argument in order to print your entire list.
Try to refactor your code a bit. It works, but it can be written better and better ;)
1) The call
System.out.println(mytrans.toString(line));
is printing out the single lineitem that is passed to it. What you probably intended was for Transaction.toString() to iterate over its list Transaction.lineItems and print each item in turn.
In fact Transaction.toString() doesn't need to take in a lineItem argument, the method should merely print out the internals of the class instance.
2) There is a similar confusion in Transacton.addItemLine(). It accepts a lineItem, prompts the user for new values, updates lineItem.. then constructs a new lineItem to store in Transaction.lineItems. It isn't actually causing a bug that I can see but you should get rid of the lineItem argument entirely; addItemLine doesn't need it.
3) Incidentally:
for (int i=0; i<2;i++){ }
loops twice, not three times. I trust you would have caught that in testing.
4) There is also a line of code near the end of addItemLine that doesn't actually do anything! Maybe you can spot that one on your own.
There are some other issues but those are the ones that leapt out at me.
Just a quick non-tested solution that may work. Something is copied from your code, something is changed because your code was wrong.
// If you create this inside the method than you'll lose everything everytime you call addItemLine
private ArrayList<lineItem> lineItems;
public void addItemLine(lineItem line){
Scanner mykey=new Scanner(System.in);
for (int i=0; i<2;i++){
String k= line.getItemName();
int m= line.getQuantity();
double d= line.getPrice();
System.out.println("enter item name:");
k = mykey.next();
line.setItemName(k);
System.out.println("enter quantity:");
m= mykey.nextInt();
line.setQuantity(m);
System.out.println("enter unit price:");
d= mykey.nextDouble();
line.setPrice(d);
line.getItemName(); line.getQuantity(); line.getPrice();
lineItems.add(new lineItem(k,m,d));
// This doesn't have to return anything, it just adds to the list
}
// No parameteres, this should build the string for the current object
public String toString() {
// String concatenation is not the best idea, StringBuilder is better
StringBuilder sb = new StringBuilder();
// If you want to print all of them then you need to iterate over the list
for (lineItem item : lineItems){
sb.append("Customer ID:" + this.getcustomerID() + "\n" + "Customer Name: " + this.getcustomerName());
for (int i=0; i<2;i++){
// Copied from your code
sb.append("\n\n" + lin.getItemName() + "\t" + "Qty" + lin.getQuantity() + " "+ "#" + lin.getPrice() + " "+ "\t" + "$" + lin.getTotalPrice());
}
sb.append("\n);
}
return sb.toString();
}
It seems that you don't understand how to create a Java object, or how to keep your application model separate from your application view.
Here's a test run of your code, after I made some changes.
Enter customer name: Gilbert
Enter customer ID: 123
Enter item name: Spinach
Enter quantity: 5
Enter unit price: .89
Customer ID: 123
Customer Name: Gilbert
Spinach Qty 5 #0.89 $4.45
Enter item name: Corn
Enter quantity: 12
Enter unit price: .29
Customer ID: 123
Customer Name: Gilbert
Corn Qty 12 #0.29 $3.4799999999999995
Enter item name:
First, let's look at your Java objects. The first Java object which you didn't include, is LineItem. Note that Java class names start with a capital letter.
package com.ggl.transaction;
public class LineItem {
private String itemName;
private int quantity;
private double price;
public LineItem(String itemName, int quantity, double price) {
this.itemName = itemName;
this.quantity = quantity;
this.price = price;
}
public String getItemName() {
return itemName;
}
public void setItemName(String itemName) {
this.itemName = itemName;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public double getTotalPrice() {
return price * quantity;
}
}
A Java object consists of class fields, and getters and setters for the fields.
Next, here's your Transaction class.
package com.ggl.transaction;
import java.util.ArrayList;
import java.util.List;
public class Transaction {
private List<LineItem> lineItems;
private int customerID;
private String customerName;
public Transaction(int customerID, String customerName) {
this.customerID = customerID;
this.customerName = customerName;
this.lineItems = new ArrayList<>();
}
public int getcustomerID() {
return customerID;
}
public void setcustomerID(int customerID) {
this.customerID = customerID;
}
public String getcustomerName() {
return customerName;
}
public void setcustomerName(String customerName) {
this.customerName = customerName;
}
public void addItemLine(LineItem line) {
this.lineItems.add(line);
}
public void updateItem(String item, int quant, double pri) {
LineItem l = new LineItem(item, quant, pri);
int m = 0;
m = l.getQuantity();
m = m + quant;
l.setQuantity(m);
}
public double getTotalPrice() {
double totalPrice = 0;
for (int i = 0; i < 2; i++) {
LineItem item = lineItems.get(i);
totalPrice = totalPrice + item.getTotalPrice();
}
return totalPrice;
}
public String getLineItem(String s, int d, double k) {
LineItem o = new LineItem(s, d, k);
for (int i = 0; i < 2; i++) {
if (!s.equals(o.getItemName()))
System.out.println("item not found");
else
s = (o.getItemName() + o.getQuantity() + o.getPrice());
}
return s;
}
public String toItemString(LineItem lin) {
String b = "";
String a = ("Customer ID: " + this.getcustomerID() + "\n"
+ "Customer Name: " + this.getcustomerName());
for (int i = 0; i < 2; i++) {
b = ("\n\n" + lin.getItemName() + "\t" + "Qty " + lin.getQuantity()
+ " " + "#" + lin.getPrice() + " " + "\t" + "$"
+ lin.getTotalPrice() + "\n");
}
return a + b;
}
}
I simplified your addItemLine class. Code that receives input using the Scanner class belongs in your TransactionTesting class.
I renamed your toString method to toItemString. toString is a method of the Object class. Since your method has a parameter, I renamed it to lessen any confusion.
Finally, here's your TransactionTesting class. I fixed it up so it would work. You can specify any number of line items. To stop processing, just enter a blank item name.
package com.ggl.transaction;
import java.util.Scanner;
public class TransactionTesting {
public static void main(String args[]) {
Scanner mykey = new Scanner(System.in);
System.out.print("Enter customer name: ");
String name = mykey.nextLine().trim();
System.out.print("Enter customer ID: ");
int id = Integer.valueOf(mykey.nextLine().trim());
Transaction mytrans = new Transaction(id, name);
boolean processing = true;
while (processing) {
System.out.print("Enter item name: ");
String k = mykey.nextLine().trim();
if (k.equals("")) {
processing = false;
} else {
System.out.print("Enter quantity: ");
int m = Integer.valueOf(mykey.nextLine().trim());
System.out.print("Enter unit price: ");
double d = Double.valueOf(mykey.nextLine().trim());
LineItem lineItem = new LineItem(k, m, d);
mytrans.addItemLine(lineItem);
System.out.println("\n" + mytrans.toItemString(lineItem));
}
}
mykey.close();
}
}
Remember, keep your application model (LineItem & Transaction) separate from your application view (TransactionTesting).
Simply put, in your method "addItemLine" you take data from 1 lineItem, overwrite it with some keyboard input, and the put in the list 2 other lineItem instances.
Then in the test code you print the original lineItem, which is not even in the list.
The method itself iterates on nothing, just creates twice the same string "b".
I suggest you to look at some tutorials on arrays and for loops.

Categories