I want to read and map the following formatted lines into java bean
80 : (1,53.38,€45) (2,88.62,€98) (3,78.48,€3) (4,72.30,€76) (5,30.18,€9)
7 : (1,10.02,€5) (2,8.2,€9) (3,7.8,€2) (4,7.0,€6) (5,3.18,€9)
So here the digit before : will be captured as a int value and will be mapped on totalWeight and repetive patterns like (1,53.38,€45) will be mapped to items
Here is my java bean
public class Package {
private double maxWeigh; \\ so the digit value before : will be here
private List<Product> products; \\ (1,53.38,€45) will be parsed to product class
public double getMaxWeigh() {
return maxWeigh;
}
public void setMaxWeigh(double maxWeigh) {
this.maxWeigh = maxWeigh;
}
public List<Product> getProducts() {
return products;
}
public void setProducts(List<Product> products) {
this.products = products;
}
}
Here is my product class
public class Product {
private int index;
private double weight;
private double cost;
private String currencySymbol;
public double getWeight() {
return weight;
}
public void setWeight(double weight) {
this.weight = weight;
}
public double getCost() {
return cost;
}
public void setCost(double cost) {
this.cost = cost;
}
public String getCurrencySymbol() {
return currencySymbol;
}
public void setCurrencySymbol(String currencySymbol) {
this.currencySymbol = currencySymbol;
}
public int getIndex() {
return index;
}
public void setIndex(int index) {
this.index = index;
}
}
This is what i tried so far but this is for only products part i want to capture whole line at once
\\((\\d+),(\\d+\\.?\\d*?),€?(\\d+)\\)
Here is a code that lets you iterate over each token (a,b,c) and retrieve their members.
It uses named capturing groups.
import java.util.regex.*;
public static void main(String[] args) {
Pattern headPattern = Pattern.compile("^(\\d+).*");
Pattern tailPattern = Pattern.compile("\\((?<p1>\\d),(?<p2>\\d+\\.\\d+),(?<p3>€\\d+)\\)");
Matcher m1 = headPattern.matcher("80 : (1,53.38,€45) (2,88.62,€98) (3,78.48,€3) (4,72.30,€76) (5,30.18,€9)");
Matcher m2 = tailPattern.matcher("80 : (1,53.38,€45) (2,88.62,€98) (3,78.48,€3) (4,72.30,€76) (5,30.18,€9)");
m1.matches();
System.out.println("p0 = " + m1.group(1));
while(m2.find()) {
System.out.println("token = " + m2.group());
System.out.println("p1 = " + m2.group("p1"));
System.out.println("p2 = " + m2.group("p2"));
System.out.println("p3 = " + m2.group("p3"));
}
}
Related
I'm made a program that creates an invoice but when it comes numbers in the thousands the output isn't neat and ruins everything. How do I fix this so the program's columns are more aligned with numbers like this? Here is the code I used to create the program. If anyone could help, it would be much appericated.
Here's the one with the main method...
public class InvoicePrinter
{
public static void main(String[] args)
{
Address samsAddress=new Address("Sam's Small Appliances", "100 Main
Street", "Anytown", "CA", "98765");
Invoice samsInvoice =new Invoice(samsAddress);
samsInvoice.add(new Product("Toaster", 29.95),3);
samsInvoice.add(new Product("Hair Dryer", 24.95),1);
samsInvoice.add(new Product("Car Vacuum",19.99),2);
samsInvoice.add(new Product("Nano Parts",100000),1);
samsInvoice.addSimple(new Product("Shipping",5.00));
System.out.println(samsInvoice.format());
}
}
These are the other programs needed for the program to work
import java.util.ArrayList;
public class Invoice
{
public Invoice(Address anAddress)
{
items=new ArrayList<LineItem>();
billingAddress=anAddress;
simpleItems= new ArrayList<SimpleLineItem>();
}
public void addSimple(Product aProduct)
{
SimpleLineItem anItem= new SimpleLineItem(aProduct);
simpleItems.add(anItem);
}
public void add(Product aProduct, int quantity)
{
LineItem anItem=new LineItem(aProduct,quantity);
items.add(anItem);
}
public String format()
{
String r=" I N V O I C E\n\n"+billingAddress.format()+String.format("\n\n%-30s%8s%5s%8s\n","Description", "Price","Qty","Total");
for(LineItem i:items)
{
r=r+i.format()+"\n";
}
for(SimpleLineItem j:simpleItems)
{
r=r+j.format() + "\n";
}
r = r + String.format("\nAMOUNT DUE: $%8.2f", getAmountDue());
return r;
}
public double getAmountDue()
{
double amountDue = 0;
for (LineItem i : items)
{
amountDue = amountDue + i.getTotalPrice();
}
for(SimpleLineItem j:simpleItems)
{
amountDue = amountDue + j.getPrice();
}
return amountDue;
}
private Address billingAddress;
private ArrayList<LineItem> items;
private ArrayList<SimpleLineItem> simpleItems;
}
Few more
public class LineItem
{
public LineItem(Product aProduct, int aQuantity)
{
theProduct = aProduct;
quantity = aQuantity;
}
public double getTotalPrice()
{
return theProduct.getPrice() *quantity;
}
public String format()
{
return String.format("%'-30s%'8.2f%'5d%'8.2f", theProduct.getDescription(),theProduct.getPrice(),quantity,getTotalPrice());
}
private int quantity;
private Product theProduct;
}
Another one
public class SimpleLineItem
{
public SimpleLineItem(Product aProduct)
{
theProduct=aProduct;
}
public double getPrice()
{
return theProduct.getPrice();
}
public String format()
{
return String.format("%-30s" +" " + "%8.2f",
theProduct.getDescription(), theProduct.getPrice());
}
private Product theProduct;
}
Two more
public class Product
{
public Product(String aDescription,double aPrice)
{
description = aDescription;
price = aPrice;
}
public String getDescription()
{
return description;
}
public double getPrice()
{
return price;
}
private String description;
private double price;
}
Last one
public class Address
{
public Address(String aName, String aStreet, String aCity, String
aState,String aZip)
{
name = aName;
street = aStreet;
city = aCity;
state = aState;
zip = aZip;
}
public String format()
{
return name + "\n" + street + "\n" + city + ", " + state + " " + zip;
}
private String name;
private String street;
private String city;
private String state;
private String zip;
}
Maybe you can take a look at the javadocs by Oracle on System.out.format and DecimalFormat class
Formatting Numeric Print Output
So basically this happens when you cannot decide the total length of your number column until you print out everything. For this you will need to set the number column's length to the lengthiest number or in your case price length and justify right all the numbers. So you'll need to add all the numbers to an array and loop through them to find the lengthiest number.
I got 5 classes, and 4 of them are working as intended.
I'm an absolut beginer with java and I hope someone can provide me with help.
its a little application to make orders and bundle orders.
my problem is the class bundleItem.
I expect to get the value of all items with a discount added to them, but I allways get negative return values.
Here are my classes
class Order
package testateins;
import java.util.ArrayList;
public class Order {
private ArrayList<Item> allOrders;
public Order(){
this.allOrders = new ArrayList<Item>();
}
public void addItem(Item item) {
this.allOrders.add(item);
}
public void removeItem(Item item) {
this.allOrders.remove(item);
}
public double getTotalprice(){
double totalprice = 0;
for(Item element : allOrders) {
totalprice += element.getPrice();
}
return totalprice;
}
public void printItems() {
for(Item element : allOrders) {
element.print();
}
}
}
Class Item
package testateins;
public abstract class Item{
String description;
double price;
public Item(String description) {
this.description = description;
}
public abstract double getPrice();
public void setItem() {
}
public void print() {
System.out.println("Beschreibung " + description);
}
}
class ProductItem
package testateins;
public class ProductItem extends Item{
public double pricePerUnit;
public double amount;
public double price;
public ProductItem(String description, int pricePerUnit, int amount) {
super(description);
this.pricePerUnit = pricePerUnit;
this.amount = amount;
this.price = amount * pricePerUnit;
}
public void print() {
System.out.println("Beschreibung " + description);
System.out.println("menge " + amount);
System.out.println("Preis pro Einheit " + pricePerUnit);
System.out.println("Gesammtpreis " + price);
}
public double getPrice() {
return this.price;
}
}
class ServiceItem
package testateins;
public class ServiceItem extends Item{
public double price;
public ServiceItem(String description, Integer packageprice) {
super(description);
this.price = packageprice;
}
public void print() {
System.out.println("Beschreibung " + description);
System.out.println("Servicepreis " + price);
}
public double getPrice() {
return this.price;
}
}
class BundleItem(my problemclass)
package testateins;
import java.util.ArrayList;
public class BundleItem extends Item {
private double rabatt;
private ArrayList<Item> allOrders;
public BundleItem(String description, double rabatt) {
super(description);
this.allOrders = new ArrayList<Item>();
setrabatt(rabatt);
}
public void setrabatt(double rabatt) {
this.rabatt = rabatt;
}
public double getrabatt() {
return this.rabatt;
}
public void addItem(Item item) {
if(item instanceof ProductItem || item instanceof ServiceItem) {
this.allOrders.add(item);
}
}
#Override
public double getPrice() {
double result = 0;
double sum = 0;
double discount = (rabatt/100);
for(Item element : allOrders) {
result+=element.getPrice();
}
return sum - (result * discount);
}
public void print() {
super.print();
System.out.println(rabatt);
for(Item element: allOrders) {
element.print();
}
}
}
and my testing class which returns negative discounts, the important part is after "part 2"
package testateins;
public class Testing {
public static void main(String[] args) {
ServiceItem wischen = new ServiceItem("wischen", 20);
System.out.println(wischen.description);
System.out.println(wischen.price);
System.out.println("___________________________");
ProductItem kuchen = new ProductItem("kuchen", 3, 15);
System.out.println(kuchen.description);
System.out.println(kuchen.amount);
System.out.println(kuchen.pricePerUnit);
System.out.println(kuchen.price);
System.out.println("___________________________");
Order simpleOrder = new Order();
simpleOrder.addItem(wischen);
simpleOrder.addItem(kuchen);
simpleOrder.addItem(kuchen);
simpleOrder.printItems();
System.out.println("___________________________");
System.out.println("totalpreis:");
System.out.println(simpleOrder.getTotalprice());
//part 2
System.out.println("--------uebung 2------------.-");
Order BundleOrder = new Order();
ProductItem heft = new ProductItem("Heft", 1, 10);
ProductItem stift = new ProductItem("Stift", 1, 10);
BundleItem Discounteins = new BundleItem("Discounteins(50)", 50);
BundleItem Discountzwei = new BundleItem("Discountzwei(50)", 50);
BundleItem Discountdrei = new BundleItem("Discounteins(10)", 10);
Discounteins.addItem(heft);
Discounteins.addItem(stift);
Discountzwei.addItem(Discounteins);
Discountzwei.addItem(wischen);
Discountzwei.addItem(wischen);
Discountdrei.addItem(wischen);
Discountdrei.addItem(wischen);
BundleOrder.addItem(Discountzwei);
BundleOrder.addItem(Discounteins);
BundleOrder.printItems();
System.out.println(BundleOrder.getTotalprice());
System.out.println("---------------------------.-");
Discounteins.setrabatt(50);
System.out.println(Discounteins.getrabatt());
BundleOrder.printItems();
System.out.println("---------------------------.---");
System.out.println(BundleOrder.getTotalprice());
System.out.println("---------------------------.----");
}
}
Your sum is always zero, that's why you always get negative values.
I suppose you intended to do something like this:
#Override
public double getPrice() {
double sum = 0;
double discount = (rabatt / 100);
for(Item element : allOrders) {
sum += element.getPrice();
}
return sum - (sum * discount);
}
Try replacing
return sum - (result * discount);
with
return result-(result * discount);
and remove the sum variable that is not used. Now
(result * discount)
will give you the total discount. And Subtracting it from result will give you the actual amount after discounts
I'm having a problem regarding a polymorphic invocation inside a loop.
I have an abstract class called Item that has two subclasses ClothingItem and SportItem and an abstract method called printBudgetGST(Items[] item) to return a string of an item with updated pricing which include tax.
Item Class :
public abstract class Item
{
private int code;
private double price;
private boolean isOnGST;
public Item()
{
}
public Item(int code,double price,boolean isOnGST)
{
this.code = code;
this.price = price;
this.isOnGST = isOnGST;
}
public void setGST(boolean isgst)
{
this.isOnGST = isgst;
}
public int getCode()
{
return code;
}
public boolean getIsOnGST()
{
return isOnGST;
}
public double getCurrentPrice()
{
return price;
}
public String toString() {
return "Item [code=" + code + ", price=" + price + ", isOnGST=" + isOnGST + "]";
}
public abstract String printBudgetGST(Item[] items);
}
ClothingItem class
public class ClothingItem extends Item
{
public ClothingItem(){
}
public ClothingItem(int code,double price,boolean isOnGST)
{
super(code,price,isOnGST);
}
#Override
public String printBudgetGST(Item[] item)
{
String stringitem ="";
for(int i=0;i<item.length;i++)
{
if(item[i].getIsOnGST()==true&&item[i].getCurrentPrice()<100.00)
{
double finalprice =(0.06*item[i].getCurrentPrice())+item[i].getCurrentPrice();
stringitem = stringitem + " " + "ClothingItem : " + item[i].getCode()+":"+"RM"+finalprice;
}
}
return stringitem;
}
}
SportsItem class:
public class SportsItem extends Item
{
public SportsItem(){
}
public SportsItem(int code,double price,boolean isOnGST)
{
super(code,price,isOnGST);
}
public String printBudgetGST(Item[] item)
{
String stringitem = "";
for(int i=0;i<item.length;i++)
{
if(item[i].getIsOnGST()==true &&item[i].getCurrentPrice()<150.00)
{
double finalprice =(0.06*item[i].getCurrentPrice())+item[i].getCurrentPrice();
stringitem = stringitem + "SportsItem : " + item[i].getCode()+":"+"RM"+finalprice;
}
}
return stringitem;
}
}
Test class :
public class Retail_Item
{
private Item[] itemList;
public Retail_Item()
{
itemList = new Item[10];
itemList[0] = new ClothingItem(10001,85,true);
itemList[1] = new ClothingItem(10002,150,false);
itemList[2] = new ClothingItem(10003,168,true);
itemList[3] = new ClothingItem(10004,43,true);
itemList[4] = new ClothingItem(10005,162,false);
itemList[5] = new SportsItem(10006,178,false);
itemList[6] = new SportsItem(10007,80,true);
itemList[7] = new SportsItem(10008,191,false);
itemList[8] = new SportsItem(10009,45,true);
itemList[9] = new SportsItem(10010,121,true);
}
public void printItem()
{
for(int i =0 ;i<itemList.length;i++)
{
if(itemList[i].getIsOnGST()==true && itemList[i].printBudgetGST(itemList).length()>0)
{
System.out.println(itemList[i].printBudgetGST(itemList));
}
}
}
}
public class TestRetailItem {
public static void main(String[] args)
{
Retail_Item ret = new Retail_Item();
ret.printItem();
}
}
OUTPUT :
The output should return a list of items which is on tax(GST) and with the updated pricing information like the example below
The problem is that you are passing to printBudgetGST the whole array of items and iterating over that array inside your implementations of printBudgetGST. Instead, you should remove that parameter and inside printBudgetGST you should simply call getCurrentPrice() and getCode() on this rather than on each item[i].
In addition, you are doing the check for maximum price (< 100 or < 150) inside the item subclasses but it's best to do this alongside the other checks in printItem. Because the max price depends on the subclass (SportsItem vs ClothinItem) I recommend you to create an abstract method boolean isOnBudget() in Item and implement accordingly in those two subclasses.
A fully fixed version of your code is
public abstract class Item {
private int code;
private double price;
private boolean isOnGST;
public Item()
{
}
public Item(int code,double price,boolean isOnGST)
{
this.code = code;
this.price = price;
this.isOnGST = isOnGST;
}
public void setGST(boolean isgst)
{
this.isOnGST = isgst;
}
public int getCode()
{
return code;
}
public boolean getIsOnGST()
{
return isOnGST;
}
public double getCurrentPrice()
{
return price;
}
public String toString() {
return "Item [code=" + code + ", price=" + price + ", isOnGST=" + isOnGST + "]";
}
public abstract String printBudgetGST();
public abstract boolean isOnBudget();
}
class ClothingItem extends Item {
public ClothingItem() {
}
public ClothingItem(int code, double price, boolean isOnGST) {
super(code, price, isOnGST);
}
#Override
public String printBudgetGST() {
String stringitem = "";
double finalprice = (0.06 * getCurrentPrice()) + getCurrentPrice();
stringitem = stringitem + " " + "ClothingItem : " + getCode() + ":" + "RM" + finalprice;
return stringitem;
}
#Override
public boolean isOnBudget() {
return getCurrentPrice() < 100.00;
}
}
class SportsItem extends Item {
public SportsItem() {
}
public SportsItem(int code, double price, boolean isOnGST) {
super(code, price, isOnGST);
}
public String printBudgetGST() {
String stringitem = "";
double finalprice = (0.06 * getCurrentPrice()) + getCurrentPrice();
stringitem = stringitem + "SportsItem : " + getCode() + ":" + "RM" + finalprice;
return stringitem;
}
#Override
public boolean isOnBudget() {
return getCurrentPrice() < 150.00;
}
}
class Retail_Item
{
private Item[] itemList;
public Retail_Item()
{
itemList = new Item[10];
itemList[0] = new ClothingItem(10001,85,true);
itemList[1] = new ClothingItem(10002,150,false);
itemList[2] = new ClothingItem(10003,168,true);
itemList[3] = new ClothingItem(10004,43,true);
itemList[4] = new ClothingItem(10005,162,false);
itemList[5] = new SportsItem(10006,178,false);
itemList[6] = new SportsItem(10007,80,true);
itemList[7] = new SportsItem(10008,191,false);
itemList[8] = new SportsItem(10009,45,true);
itemList[9] = new SportsItem(10010,121,true);
}
public void printItem() {
for(int i =0 ;i<itemList.length;i++) {
if(itemList[i].getIsOnGST()==true && itemList[i].printBudgetGST().length()>0 && itemList[i].isOnBudget())
{
System.out.println(itemList[i].printBudgetGST());
}
}
}
}
class TestRetailItem {
public static void main(String[] args) {
Retail_Item ret = new Retail_Item();
ret.printItem();
}
}
I am new to Java and I am working on a project that works with calculating prices with/without employee discounts. After reading the following code could someone explain to me how I might go about changing the parent class method outputs from the child class in order to get the correct outputs for my program?
Parent Class (I am NOT allowed to edit this):
public class GroceryBill {
private Employee clerk;
private List<Item> receipt;
private double total;
private double internalDiscount;
public GroceryBill(Employee clerk) {
this.clerk = clerk;
receipt = new ArrayList<Item>();
total = 0.0;
internalDiscount = 0.0;
}
public void add(Item i) {
receipt.add(i);
total += i.getPrice();
internalDiscount += i.getDiscount();
}
public double getTotal() {
return Math.rint(total * 100) / 100.0;
}
public Employee getClerk() {
return clerk;
}
public void printReceipt() {
System.out.println(this);
}
private String valueToString(double value) {
value = Math.rint(value * 100) / 100.0;
String result = "" + Math.abs(value);
if(result.indexOf(".") == result.length() - 2) {
result += "0";
}
result = "$" + result;
return result;
}
public String receiptToString() {
String build = "items:\n";
for(int i = 0; i < receipt.size(); i++) {
build += " " + receipt.get(i);
if(i != receipt.size() - 1) {
build += "\n";
}
}
return build;
}
public String toString() {
return receiptToString() + "\ntotal: " + valueToString(total);
}
public String discountToString() {
return receiptToString() + "\nsub-total: " + valueToString(total) + "\ndiscount: " + valueToString(internalDiscount) + "\ntotal: " + valueToString(total - internalDiscount);
}
public static class Employee {
private String name;
public Employee(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
public static class Item {
private String name;
private double price;
private double discount;
public Item(String name, double price, double discount) {
this.name = name;
this.price = price;
this.discount = discount;
}
public double getPrice() {
return price;
}
public double getDiscount() {
return discount;
}
private String valueToString(double value) {
String result = "" + Math.abs(value);
if(result.indexOf(".") == result.length() - 2) {
result += "0";
}
result = "$" + result;
return result;
}
public String toString() {
return name + " " + valueToString(price) + " (-" + valueToString(discount) + ")";
}
}
}
Here is my code:
public class DiscountBill extends GroceryBill
{
private int myDiscountCount;
private double myDiscountAmount;
private double myPrice;
public DiscountBill(Employee clerk, boolean preferred)
{
super(clerk);
String name = "";
double price = 0;
double discount = 0;
Object myItem = new Item(name, price, discount);
myPrice = ((GroceryBill.Item) myItem).getPrice() - ((GroceryBill.Item) myItem).getDiscount();
GroceryBill.Item myBill = new GroceryBill.Item(name, price, discount);
myDiscountAmount = myBill.getDiscount();
if (myDiscountAmount > 0 && preferred)
{
myDiscountCount++;
}
}
/*
public double getTotal()
{
Override goes here?
}
*/
public int getDiscountCount()
{
return myDiscountCount;
}
public double getDiscountAmount()
{
return myDiscountAmount;
}
public double getDiscountPercent()
{
return (myPrice / getDiscountCount()) * 100;
}
}
Lastly, here is the expected output:
P.S. Please let me know if I need to give more/less information and ways that I can clean up this post or make it easier to understand. If my question was too broad, please ask me what you don't understand about it and I'll try my best to tell you! Thank you!
I am a student working on a project creating classes with arrays to model composition. I have assume I have everything right so far but it seem that I am getting a problem with my print statement in the driver class. I am not sure if it about the way I am method chaining the two together. Any information would be thankful.
public class MyWord
{
private String word;
public MyWord(){
word = "Null";
}
public MyWord(String s){
word = s;
}
public String getWord(){
return word;
}
public void setWord(String w){
word = w;
}
public void print(){
System.out.println(word);
}
}
public class Page
{
private MyWord[] words = new MyWord[5];
private int pageNumber;
public Page(){
MyWord words[] = {} ;
pageNumber = 0;
}
public Page(MyWord[] a, int b){
words = a;
pageNumber = b;
}
public MyWord[] getWord(){
return words;
}
public int getPageNumber(){
return pageNumber;
}
public void setMyWord(MyWord[] a){
words = a;
}
public void setPageNumber(int b){
pageNumber = b;
}
public void print(){
System.out.print(" Page Number: " + pageNumber + " " + words);
}
}
public class Book
{
private Page[] p = new Page[5];
private String title;
public Book(){
Page[] p = {};
title = " ";
}
public Book(Page[] pa, String ti){
p = pa;
title = ti;
}
public Page[] getPage(){
return p;
}
public String getTitle(){
return title;
}
public void setPage(Page[] x){
p = x;
}
public void setTitle(String y){
title = y;
}
public void print(){
System.out.print("Book info:" + p + " " + title);
}
}
public class Series
{
private Book bookOne, bookTwo, bookThree;
private double price;
public Series(){
bookOne = null;
bookTwo = null;
bookThree = null;
price = 0;
}
public Series(Book one, Book two, Book three, double p){
bookOne = one;
bookTwo = two;
bookThree = three;
price = p;
}
public Book getBookTwo(){
return bookTwo;
}
public Book getBookOne(){
return bookOne;
}
public Book getBookThree(){
return bookThree;
}
public double getPrice(){
return price;
}
public void setBookOne(Book bookOne){
this.bookOne = bookOne;
}
public void setBookTwo(Book bookTwo){
this.bookTwo = bookTwo;
}
public void setBookThree(Book bookThree){
this.bookThree = bookThree;
}
public void setPrice(double price){
this.price = price;
}
public void print(){
System.out.println("Series info");
System.out.println("Book one:" + bookOne + " Book Two: " +bookTwo
+ " Book Three: " + bookThree + "Price: " + price);
}
}
public class Driver
{
public static void main(String args[]){
MyWord[] w1 = new MyWord[2];
w1[0] = new MyWord("Hello");
w1[1] = new MyWord("Hola");
Page[] p = new Page[2];
p[0] = new Page(w1, 20);
p.print();
}
}
p is of type Page[], i.e. "array of Page". And arrays don't have a print() method. So the statement p.print() doesn't compile (you should have said that in your question, and joined the exact error message).
To print all the pages of the array, you need to loop over the array:
for (Page page : p) {
page.print();
}
Please avoid single-letter variables, and use a plural form for arrays and collections: Page[] pages = new Page[2];