How to format output console columns in java? - java

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.

Related

Trouble accessing data from java program

I'm having a goofy issue. I'm trying to see if I can printout the restaurants and employees data I have here and I can't remember how best to do it this.
Once I can figure out how to do that, I'll be able to create methods using it, but I can't seem to remember how to do it this way.
Updated Code
class Main {
public static void main(String[] args) {
Employee john = new Employee("John","asian",35.00);
Employee sam = new Employee("Sam","Greek",25.00);
Employee michael = new Employee("Michael","Italian",50.00);
Restaurant asian = new Restaurant("Asian","asian",25.00);
Restaurant greek = new Restaurant("greek","greek",25.00);
Restaurant italian = new Restaurant("italian","italian",25.00);
}
public static class Restaurant {
private String restaurantName;
private String cuisine;
private double price;
public Restaurant( String restaurantName,
String cuisine,
double price) {
this.restaurantName = restaurantName;
this.cuisine = cuisine;
this.price = price;
}
public String getRestaurantName() {
return restaurantName;
}
public String getCuisine() {
return cuisine;
}
public double getPrice() {
return price;
}
}
public static class Employee {
private String employeeName;
private String cuisine;
private double budget;
public Employee(String employeeName,
String cuisine,
double budget) {
this.employeeName = employeeName;
this.cuisine = cuisine;
this.budget = budget;
}
public String getEmployeeName() {
return employeeName;
}
public String getCuisine() {
return cuisine;
}
public double getBudget() {
return budget;
}
}
}
For printing out the data of an object you can override the toString method.
After that, the class Restaurant looks like this.
public static class Restaurant {
private String restaurantName;
private String cuisine;
private double price;
public Restaurant( String restaurantName,
String cuisine,
double price) {
this.restaurantName = restaurantName;
this.cuisine = cuisine;
this.price = price;
}
public String getRestaurantName() {
return restaurantName;
}
public String getCuisine() {
return cuisine;
}
public double getPrice() {
return price;
}
#Override
public String toString() {
return "Restaurant [restaurantName=" + restaurantName + ", cuisine=" + cuisine + ", price=" + price + "]";
}
}
the class Employee looks like this.
public static class Employee {
private String employeeName;
private String cuisine;
private double budget;
public Employee(String employeeName,
String cuisine,
double budget) {
this.employeeName = employeeName;
this.cuisine = cuisine;
this.budget = budget;
}
public String getEmployeeName() {
return employeeName;
}
public String getCuisine() {
return cuisine;
}
public double getBudget() {
return budget;
}
#Override
public String toString() {
return "Employee [employeeName=" + employeeName + ", cuisine=" + cuisine + ", budget=" + budget + "]";
}
}
and then you can print an object in sysout
System.out.println(michael);
You have to use a toString method() for each Object's class.
For example in Employee Class:
public String toString()
{
String str = "Employee Name: " + employeeName +
"\nCuisine: " + cuisine + "\nBudget: " + budget;
return str;
}
After that you just have to use the toString() in the main() method:
System.out.println(john.toString());
In the main method you could also use an array to store the data and make it easier to access. Then to display both of the objects inside you could use just one for loop, but I used two to keep the outputs separate from one another.
int numEmployees = 3;
Employee myEmployees[] = new Employee[numEmployees];
myEmployees[0] = new Employee("John","asian",35.00); // Stores John in index 0...
myEmployees[1] = new Employee("Sam","Greek",25.00);
myEmployees[2] = new Employee("Michael","Italian",50.00);
// Displays each object who's index is associated with the value for i
for(int i = 0; i < employees.length; i++)
System.out.println(myEmployees[i].toString());
int numRestaurants = 3;
Restaurant myRestaurants = new Restaurant[numRestaurant]
myRestaurants[0] = new Restaurant("Asian","asian",25.00); // Stores Asain in index 0...
myRestaurants[1] = new Restaurant("greek","greek",25.00);
myRestaurants[2] = new Restaurant("italian","italian",25.00);
// Displays each object who's index is associated with the value for i
for(int i = 0; i < restaurants.length; i++)
System.out.println(myRestaurants[i].toString());

How do I create an boolean equals method compares objects in an array

My programming assignment tasked me with writing an increase/decreasePay abstract method that must be put in my abstract employee class. I can't seem to get the the method correct in HourlyWorker so that it will take increase or decrease the pay by a "percentage". My math is sound (monthly pay - or + (monthly pay * the percentage), but my output in my test class is coming out the same after increasing/decreasing pay. Any help?
Employee class:
abstract public class Employee
{
private String lastName;
private String firstName;
private String ID;
public abstract void increasePay(double percentage);
public abstract void decreasePay(double percentage);
public abstract double getMonthlyPay();
public Employee(String last, String first, String ID)
{
lastName = last;
firstName = first;
this.ID = ID;
}
public void setLast(String last)
{
lastName = last;
}
public void setFirst(String first)
{
firstName = first;
}
public void setIdNumber(String ID)
{
this.ID = ID;
}
public String getLastName()
{
return lastName;
}
public String getFirstName()
{
return firstName;
}
public String getName()
{
return firstName + lastName;
}
public String getIdNumber()
{
return ID;
}
}
HourlyWorkerClass
public class HourlyWorker extends Employee
{
private int hours;
private double hourlyRate;
private double monthlyPay;
public HourlyWorker(String last, String first, String ID, double rate)
{
super(last, first, ID);
hourlyRate = rate;
}
public void setHours(int hours)
{
this.hours = hours;
}
public int getHours()
{
return hours;
}
public void setHourlyRate(double rate)
{
if ( hours > 160 )
this.hourlyRate = hourlyRate * 1.5;
else
this.hourlyRate = rate;
}
public double getHourlyRate()
{
return hourlyRate;
}
public void setMonthlyPay(double monthlyPay)
{
monthlyPay = hourlyRate * hours;
}
public double getMonthlyPay()
{
return hourlyRate * hours;
}
public void increasePay(double percentage)
{
monthlyPay = monthlyPay* percentage;
}
public void decreasePay(double percentage)
{
monthlyPay = monthlyPay* percentage;
}
public String toString()
{
String result = "Name: " + getFirstName() + " " + getLastName() + "\nID: "
+ getIdNumber() + " \nHourly Rate: " + hourlyRate;
return result;
}
}
Testing class (currently testing increase
public class TestEmployee2
{
public static void main(String[] args)
{
Employee [] staff = new Employee[3];
Supervisor sup = new Supervisor("Boss", "Jim", "JB7865", 54000);
HourlyWorker hw1 = new HourlyWorker("Bee", "Busy", "BB1265", 11.95);
hw1.setHours(200);
staff[0] = sup;
staff[1] = hw1;
System.out.println(staff[0].getMonthlyPay());
staff[0].increasePay(5);
System.out.println(staff[0].getMonthlyPay());
System.out.println(staff[1].getMonthlyPay());
staff[1].increasePay(10);
System.out.println(staff[1].getMonthlyPay());
}
}
Supervisor class:
public class Supervisor extends Employee
{
private double annualSalary;
private double monthlyPay;
public Supervisor(String last, String first, String ID, double salary)
{
super(last, first, ID);
annualSalary = salary;
}
public void setAnnualSalary(double salary)
{
annualSalary = salary;
}
public double getAnnualSalary()
{
return annualSalary;
}
public double getMonthlyPay()
{
return ((annualSalary + (annualSalary * .02)) / 12);
}
public void increasePay(double percentage)
{
monthlyPay = monthlyPay* percentage;
}
public void decreasePay(double percentage)
{
monthlyPay = monthlyPay* percentage;
}
public String toString()
{
String result = "Name: " + getFirstName() + " " + getLastName() + "\nID: "
+ getIdNumber() + "\nAnnual Salary: " + annualSalary;
return result;
}
}
Output is:
4590.0 4590.0 2390.0 2390.0
Doesn't appear to be modifying getMonthlyPay()
Should be:
4590.00 4819.50 2390.00 2629.00
Generally, when implementing equals(), you compare “key” fields whose values don’t change for the entity, and don’t compare “state” fields whose values change from time to time.
You are comparing sharePrice, when I believe you should be comparing symbol.
When you do list.indexOf(temp), what that does, right now, is look for a Stock that is equals to the argument passed to it -- so it looks for a Stock with price zero, not caring about the symbol at all. That's what the code does right now.
Honestly, using indexOf and equals is not really appropriate for this problem. indexOf is really only useful when you have something that's totally equal to the target you're looking for.
The best way to do something like this is
Optional<Stock> foundStock = list.stream().filter(stock -> stock.getName().equals(symbol)).findAny();
if (foundStock.isPresent()) {
// do something with foundStock.get()
} else {
// no found stock
}
indexOf() is a method return the index of the first occurrence of the specified element in the returned list. If the list does not contain this element, value -1 is returned.
More formally, return the lowest index i that meets the following conditions:
if(o==null? get(i)==null :o.equals(get(i))){
return i;
}
return -1;
If there is no such index, return -1.
And you have override the equals method, I guess you just want to focus on the same price Stock?:
#Override
public boolean equals(Object obj){
if (obj instanceof Stock){
Stock other = (Stock) obj;
return getPrice() == other.getPrice();
}
return false;
}
As my opinion, you have use List<Stock> list so the Object in the list is all Stock. Maybe it could be simplifed:
#Override
public boolean equals(Object obj){
Stock other = (Stock) obj;
return getPrice() == other.getPrice();
}

I don't know how to do an array to store for each semester the details. I am supposed to create a subclass of the class Student

The question wants me to do:
An array of Finance called financeRecord to store the details
of the payments for each semester.
This is my code
package lab5;
class Student_U extends Student {
public String student_name;
private String studentID;
public int student_age;
private byte currentSemester;
private byte TotalFinanceRecord;
private String cohort;
public Student_U() {
student_name = " ";
studentID = " ";
student_age = 0;
currentSemester = 1;
TotalFinanceRecord = 0;
cohort = " ";
}
public Student_U(String student_name, String studentID, int student_age,
String course, String year,
String section, String subject, String student_name2,
String studentID2, int student_age2,
byte currentSemester, byte totalFinanceRecord, String cohort) {
super(student_name, studentID, student_age, course, year,
section, subject);
student_name = student_name2;
studentID = studentID2;
student_age = student_age2;
this.currentSemester = currentSemester;
TotalFinanceRecord = totalFinanceRecord;
this.cohort = cohort;
}
public String getStudent_name() {
return student_name;
}
public void setStudent_name(String student_name) {
this.student_name = student_name;
}
public String getStudentID() {
return studentID;
}
public void setStudentID(String studentID) {
this.studentID = studentID;
}
public int getStudent_age() {
return student_age;
}
public void setStudent_age(int student_age) {
this.student_age = student_age;
}
public byte getCurrentSemester() {
return currentSemester;
}
public void setCurrentSemester(byte currentSemester) {
this.currentSemester = currentSemester;
}
public byte getTotalFinanceRecord() {
return TotalFinanceRecord;
}
public void setTotalFinanceRecord(byte totalFinanceRecord) {
TotalFinanceRecord = totalFinanceRecord;
}
public String getCohort() {
return cohort;
}
public void setCohort(String cohort) {
this.cohort = cohort;
}
public void initStudent() {
}
public void print() {
System.out.print("Student name: " + student_name + " ");
System.out.print("\nMatric No: " + studentID + " ");
System.out.print("\nAge: " + student_age + " ");
System.out.print("\nCurrent Semester: " + currentSemester + " ");
System.out.print("\nCohort: " + cohort + " ");
System.out.println();
}
}
Please help me fix my code I would appreciate it so much.
This is my lab assignment which needs to be submitted by tomorrow.
You could try this, but it's also better to review standard java concepts (arrays, classes, etc). After, just adapt your code as suitable.
public class Finance extends Student
{
public static void main(String args[])
{
Finance f1 = new Finance("Student_1");
System.out.println(f1);
f1.setPayment(1, 10);
System.out.println(f1);
f1.setPayment(2, 10.77);
System.out.println(f1);
Student s2 = new Student("Student 2");
Finance f2 = new Finance(s2);
f2.setPayment(2, 88.77);
System.out.println(f2);
}
Double finaceRecord[] = new Double[3];
private void initPayment()
{
for(int i=0;i<finaceRecord.length;i++)
{
finaceRecord[i]=0.0;
}
}
public Finance(Student s)
{
super(s.name);
initPayment();
}
public Finance(String name)
{
super(name);
initPayment();
}
//store first or second
public void setPayment(int i, double d)
{
if(d<=0) return;
if(i==1)
{
finaceRecord[i] = d;
}
else
{
finaceRecord[2] = d;
}
finaceRecord[0] = finaceRecord[2] + finaceRecord[1];
}
public String toString()
{
return "name="+super.name+", Total Paid="+finaceRecord[0]+","
+ " Sem1="+finaceRecord[1]+", Sem2="+finaceRecord[2];
}
}
...
public class Student
{
String name;
int Semester;
Student(String name)
{
this.name = name;
this.Semester = 1;
}
}
Ouptut
name=Student_1, Total Paid=0.0, Sem1=0.0, Sem2=0.0
name=Student_1, Total Paid=10.0, Sem1=10.0, Sem2=0.0
name=Student_1, Total Paid=20.77, Sem1=10.0, Sem2=10.77
name=Student 2, Total Paid=88.77, Sem1=0.0, Sem2=88.77
from what I understand you are supposed to create an array of Finance type
Finance []financeRecord = new Finance[totalFinanceRecord];
and then you can access the values of Finance class
financeRecord[indexNumber].methodName();

Regex to read the following formatted string pattern

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

java:29: error: cost has private access in RetailItem

Alright so I need help here I created a cash register java file and a retailItem file in my cash register file it cant read a section i put in retailItem because its private. So my question is how do i access that private variable that i wrote in my retailItem class into the cash register file
So here's my code for retailItem
import java.text.DecimalFormat;
public class RetailItem
{
private String description;
private double price;
private double unitsOnHand;
private CostData cost;
public void setDescription(String userDescription)
{
description = userDescription;
}
public void setPrice(double p)
{
price = p;
}
public void setUnitsOnHand(double userUnitsOnHand)
{
unitsOnHand = userUnitsOnHand;
}
public String getDescription()
{
return description;
}
public double getPrice()
{
return price;
}
public double getUnitsOnHand()
{
return unitsOnHand;
}
public RetailItem(RetailItem object2)
{
description = object2.description;
price = object2.price;
unitsOnHand = object2.unitsOnHand;
cost = new CostData(object2.cost.wholeSale,object2.cost.Retail);
}
public RetailItem( String descriptionGet,double pri, double
unitsOnHandGet,double wholeSale,double retail)
{
description = descriptionGet;
price = pri;
unitsOnHand = unitsOnHandGet;
cost = new CostData(wholeSale,retail);
}
public String toString()
{
String str;
DecimalFormat dollar = new DecimalFormat("#,##0.00");
str = "Description: " + description +
"Item Price: " + price +
"\nItem Number: " + unitsOnHand +
"\nWhole Cost: $" + dollar.format(cost.wholeSale) +
"\nRetail Price: $" + dollar.format(cost.Retail);
return str;
}
public class CostData
{
public double wholeSale;
public double Retail;
public CostData(double whole,double re)
{
wholeSale = whole;
Retail = re;
}
public void setRetail(double re)
{
Retail = re;
}
public void setWholeSale(double whole)
{
wholeSale = whole;
}
public double getRetail()
{
return Retail;
}
public double getWholeSale()
{
return wholeSale;
}
}
}
Here is the Cash Register class:
public class CashRegister
{
private RetailItem retail;
private int quantityItem;
private final double SALES_TAX = 0.06;
private int subTotal;
public CashRegister()
{
quantityItem = 0;
subTotal = 0;
}
public CashRegister(RetailItem retailObject,int quantity)
{
retail = new RetailItem(retailObject);
quantityItem = quantity;
}
public RetailItem getRetailItem()
{
return new RetailItem(retail);
}
public double getSubTotal()
{
return quantityItem * retail.cost.getRetail();//Here is where the problem is
}
public double getTax()
{
return SALES_TAX;
}
public double getTotal()
{
return subTotal + SALES_TAX;
}
}
You have a number of options:
If they are in the same package, you can set the access of cost to
default (remove the word private from in front of it.)
Change cost from private to public.
Create a default access (neither private nor public) getCost() method to return cost.
Create a public getCost() method to return cost.
The first option gives read/write access to any class in the same package as RetailItem.
The second option gives read/write access to all classes.
The fourth option gives read-only access to all classes.
protected access could also be an option. Its like package access, but also gives read/write access to subclasses.
See also: In Java, difference between default, public, protected, and private

Categories

Resources