I have a method that is supposed to replenish stock parts for a manufacturer. I have tried using super.Method() but its not working. There's also a class called Part if it's needed.
Main Class
package main;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class TestAssembledPart {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
List<AssembledPart> aparts = new ArrayList<AssembledPart>();
aparts.add(new AssembledPart("a200", "Crank & Pedal", 10, 3.5, "Crank", "Pedal"));
System.out.println("part before stock level change - start");
System.out.println(AssembledPart.toAssembledString(aparts));
for (AssembledPart apart: aparts){
if(apart!=null){
System.out.println("Please enter replenish quantity");
aparts.replenish(sc.nextInt());
}
}
System.out.println("part before stock level change - end");
System.out.println(AssembledPart.toAssembledString(aparts));
}
}
AssembledPart Class
package main;
import java.util.*;
public class AssembledPart extends Part {
private String basica;
private String basicb;
private int assembledstocklevel;
public AssembledPart(String id, String name, int stocklevel, double unitprice,
String basica, String basicb) {
super(id, name, stocklevel, unitprice);
this.basica = basica;
this.basicb = basicb;
}
public void replenish(int qty){
super.replenish(qty);
//super.stocklevel = super.stocklevel + qty;
}
public String toAssembledString() {
return super.toString() + " | " + basica + " | " + basicb;
}
public static String toAssembledString(Collection<AssembledPart> aparts){
String s = "";
for (AssembledPart apart: aparts){
s += apart.toAssembledString() + "\n";
}
return s;
}
}
PartClass
package main;
import java.util.*;
public class Part {
private String id;
private String name;
protected int stocklevel;
private double unitprice;
private int qty = 6000;
public Part(String id, String name, int stocklevel, double unitprice){
this.id = id;
this.name = name;
this.stocklevel = stocklevel;
this.unitprice = unitprice;
}
String partsAvailable()
{
//String newLine = System.getProperty("line.separator");
return (id + "\t" + name + "\t " + stocklevel + "\t\t " + unitprice);
}
public String getID() {
return id;
}
public void setID(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getStockLevel(){
return stocklevel - qty;
}
public void setStockLevel(int stocklevel){
this.stocklevel = stocklevel;
}
public double getUnitPrice(){
return unitprice;
}
public void setUnitPrice(double unitprice){
this.unitprice = unitprice;
}
public void replenish(int qty){
this.stocklevel = stocklevel + qty;
}
public double supply(int qty){
return unitprice * qty;
}
public String toString() {
return id + " | " + name + " | " + stocklevel + " | " + unitprice;
}
public static String toString(Collection<Part> parts){
String s = "";
for (Part part: parts){
s += part + "\n";
}
return s;
}
}
Replace this line :
aparts.replenish(sc.nextInt());
With the following
apart.replenish(sc.nextInt());
You were actually calling a method on the collection that contains your objects instead of the objects themself.
Related
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());
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();
I´m using JPA 2.2(Openjpa) running on OpenLiberty and mysqlVer 15.1 Distrib 10.1.21-MariaDB.
I have an object call Account where I use the entityManager.find to retrieve a given record.
The record is indeed retrieved but only this column "status" returns null.
But when I do the manual select against the DB,the value is there.
My Entity class
Account
package br.com.rsm.model;
import java.io.Serializable;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.OrderBy;
import javax.persistence.Table;
import javax.persistence.Transient;
//#XmlRootElement
#Entity
#Table(name = "tb_account")
#NamedQueries({
#NamedQuery(name="Account.findByEmail", query="SELECT a FROM Account a where a.email = :email"),
#NamedQuery(name="Account.findByCpf", query="SELECT a FROM Account a where a.cpf = :cpf"),
#NamedQuery(name="Account.findByUserId", query="SELECT a FROM Account a where a.userId = :userId")
})
public class Account implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String userId;
private String fullname;
private String email;
private String birthdate;
private String cpf;
private String rg;
private String address;
private String addressNumber;
private String complement;
private String cep;
private String state;
private int city;
private String phone;
private String mobile;
private String carrier;
#Column(name = "status")
private String status;
private long leftSide;
private long rightSide;
private Timestamp created;
private String parentId;
private String parentSide;
private String networkSide;
private Timestamp activated;
private double points;
private String nickname;
private String nis;
private String whatsapp;
private long bank;
private String accountType;
private String branchNumber;
private String branchDigit;
private String accountNumber;
private String accountDigit;
private String accountOwner;
private String cpfAccountOwner;
private String facebookID;
private double career;
private double pb;
private int certID;
private String automaticRenovation;
private String emailPagamento;
#Transient
private Account rightSideAccount;
#Transient
private Account leftSideAccount;
#Transient
private boolean searchableBySignedInUser;
#Transient
private long totalCandidatosAgente;
#Transient
private long totalAgentes;
#Transient
private long totalAgentesBracoEsq;
#Transient
private long totalAgentesBracoDir;
#Transient
private long totalAnjos;
#Transient
private boolean cfaCompleto;
//#Transient
#OneToMany(cascade={CascadeType.ALL}, fetch = FetchType.LAZY, orphanRemoval = true)
#JoinColumn(name = "owner" )
List<Ticket> tickets = new ArrayList<Ticket>();
#OneToMany(cascade={CascadeType.ALL}, fetch = FetchType.LAZY, orphanRemoval = true)
#OrderBy("created DESC")
#JoinColumn(name = "accountId" )
private List<Score> scores = new ArrayList<Score>();
#OneToMany(cascade={CascadeType.ALL}, fetch = FetchType.LAZY, orphanRemoval = true)
#OrderBy("activated DESC")
#JoinColumn(name = "idAccount" )
private List<ProductAccount> productsAccount = new ArrayList<ProductAccount>();
#OneToMany(cascade={CascadeType.ALL}, fetch = FetchType.LAZY, orphanRemoval = true)
#JoinColumn(name = "origin" )
private List<Trade> trades = new ArrayList<Trade>();
/**
* Construtor
*/
public Account() {}
public List<Trade> getTrades() {
return trades;
}
public void setTrades(List<Trade> trades) {
this.trades = trades;
}
public List<ProductAccount> getProductsAccount() {
return productsAccount;
}
public void setProductsAccount(List<ProductAccount> productsAccount) {
this.productsAccount = productsAccount;
}
public List<Score> getScores() {
return scores;
}
public void setScores(List<Score> scores) {
this.scores = scores;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getFullname() {
return fullname;
}
public void setFullname(String fullname) {
this.fullname = fullname;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getBirthdate() {
return birthdate;
}
public void setBirthdate(String birthdate) {
this.birthdate = birthdate;
}
public String getCpf() {
return cpf;
}
public void setCpf(String cpf) {
this.cpf = cpf;
}
public String getRg() {
return rg;
}
public void setRg(String rg) {
this.rg = rg;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getAddressNumber() {
return addressNumber;
}
public void setAddressNumber(String addressNumber) {
this.addressNumber = addressNumber;
}
public String getComplement() {
return complement;
}
public void setComplement(String complement) {
this.complement = complement;
}
public String getCep() {
return cep;
}
public void setCep(String cep) {
this.cep = cep;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public int getCity() {
return city;
}
public void setCity(int city) {
this.city = city;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getMobile() {
return mobile;
}
public void setMobile(String mobile) {
this.mobile = mobile;
}
public String getCarrier() {
return carrier;
}
public void setCarrier(String carrier) {
this.carrier = carrier;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public long getLeftSide() {
return leftSide;
}
public void setLeftSide(long leftSide) {
this.leftSide = leftSide;
}
public long getRightSide() {
return rightSide;
}
public void setRightSide(long rightSide) {
this.rightSide = rightSide;
}
public Timestamp getCreated() {
return created;
}
public void setCreated(Timestamp created) {
this.created = created;
}
public String getParentId() {
return parentId;
}
public void setParentId(String parentId) {
this.parentId = parentId;
}
public String getParentSide() {
return parentSide;
}
public void setParentSide(String parentSide) {
this.parentSide = parentSide;
}
public String getNetworkSide() {
return networkSide;
}
public void setNetworkSide(String networkSide) {
this.networkSide = networkSide;
}
public List<Ticket> getTickets() {
return tickets;
}
public void setTickets(List<Ticket> tickets) {
this.tickets = tickets;
}
public Timestamp getActivated() {
return activated;
}
public void setActivated(Timestamp activated) {
this.activated = activated;
}
public double getPoints() {
return points;
}
public void setPoints(double points) {
this.points = points;
}
#Transient
public String getShortName() {
if(fullname==null){
return "";
}
if (nickname == null || nickname.isEmpty() ) {
nickname = fullname;
}
if(nickname != null || !nickname.isEmpty()){
String[] arrTmp = fullname.replace("\n", " ").split(" ");
String shortName = "";
if(arrTmp.length >= 2){
shortName = arrTmp[0] + " " + arrTmp[1] ;
}else if(arrTmp.length >= 1){
shortName = arrTmp[0];
}
//Passo o limitador de tamanho para ambas situações.
if(shortName!=null){
if(shortName.length() > 20){
shortName = fullname.substring(0, 19) + "...";
}
}
return shortName;
}
return "";
}
public String getNickname() {
return nickname;
}
public void setNickname(String nickname) {
this.nickname = nickname;
}
public String getNis() {
return nis;
}
public void setNis(String nis) {
this.nis = nis;
}
public String getWhatsapp() {
return whatsapp;
}
public void setWhatsapp(String whatsapp) {
this.whatsapp = whatsapp;
}
public long getBank() {
return bank;
}
public void setBank(long bank) {
this.bank = bank;
}
public String getAccountType() {
return accountType;
}
public void setAccountType(String accountType) {
this.accountType = accountType;
}
public String getBranchNumber() {
return branchNumber;
}
public void setBranchNumber(String branchNumber) {
this.branchNumber = branchNumber;
}
public String getBranchDigit() {
return branchDigit;
}
public void setBranchDigit(String branchDigit) {
this.branchDigit = branchDigit;
}
public String getAccountNumber() {
return accountNumber;
}
public void setAccountNumber(String accountNumber) {
this.accountNumber = accountNumber;
}
public String getAccountDigit() {
return accountDigit;
}
public void setAccountDigit(String accountDigit) {
this.accountDigit = accountDigit;
}
public String getAccountOwner() {
return accountOwner;
}
public void setAccountOwner(String accountOwner) {
this.accountOwner = accountOwner;
}
public String getCpfAccountOwner() {
return cpfAccountOwner;
}
public void setCpfAccountOwner(String cpfAccountOwner) {
this.cpfAccountOwner = cpfAccountOwner;
}
public String getFacebookID() {
return facebookID;
}
public void setFacebookID(String facebookID) {
this.facebookID = facebookID;
}
public double getCareer() {
return career;
}
public void setCareer(double career) {
this.career = career;
}
public double getPb() {
return pb;
}
public void setPb(double pb) {
this.pb = pb;
}
public int getCertID() {
return certID;
}
public void setCertID(int certID) {
this.certID = certID;
}
public String getAutomaticRenovation() {
return automaticRenovation;
}
public void setAutomaticRenovation(String automaticRenovation) {
this.automaticRenovation = automaticRenovation;
}
public String getEmailPagamento() {
return emailPagamento;
}
public void setEmailPagamento(String emailPagamento) {
this.emailPagamento = emailPagamento;
}
public Account getRightSideAccount() {
return rightSideAccount;
}
public void setRightSideAccount(Account rightSideAccount) {
this.rightSideAccount = rightSideAccount;
}
public Account getLeftSideAccount() {
return leftSideAccount;
}
public void setLeftSideAccount(Account leftSideAccount) {
this.leftSideAccount = leftSideAccount;
}
public boolean isSearchableBySignedInUser() {
return searchableBySignedInUser;
}
public void setSearchableBySignedInUser(boolean searchableBySignedInUser) {
this.searchableBySignedInUser = searchableBySignedInUser;
}
public long getTotalCandidatosAgente() {
return totalCandidatosAgente;
}
public void setTotalCandidatosAgente(long totalCandidatosAgente) {
this.totalCandidatosAgente = totalCandidatosAgente;
}
public long getTotalAgentes() {
return totalAgentes;
}
public void setTotalAgentes(long totalAgentes) {
this.totalAgentes = totalAgentes;
}
public long getTotalAgentesBracoEsq() {
return totalAgentesBracoEsq;
}
public void setTotalAgentesBracoEsq(long totalAgentesBracoEsq) {
this.totalAgentesBracoEsq = totalAgentesBracoEsq;
}
public long getTotalAgentesBracoDir() {
return totalAgentesBracoDir;
}
public void setTotalAgentesBracoDir(long totalAgentesBracoDir) {
this.totalAgentesBracoDir = totalAgentesBracoDir;
}
public long getTotalAnjos() {
return totalAnjos;
}
public void setTotalAnjos(long totalAnjos) {
this.totalAnjos = totalAnjos;
}
public boolean isCfaCompleto() {
return cfaCompleto;
}
public void setCfaCompleto(boolean cfaCompleto) {
this.cfaCompleto = cfaCompleto;
}
/**
* Adiciona uma nova classe Score
* #param score Score
*/
public void addScore(Score score) {
getScores().add(score);
}
public void addProductAccount(ProductAccount productAccount) {
getProductsAccount().add(productAccount);
}
public void addTrade(Trade trade) {
getTrades().add(trade);
}
#Override
public String toString() {
return "Account [id=" + id + ", userId=" + userId + ", fullname=" + fullname + ", email=" + email
+ ", birthdate=" + birthdate + ", cpf=" + cpf + ", rg=" + rg + ", address=" + address
+ ", addressNumber=" + addressNumber + ", complement=" + complement + ", cep=" + cep + ", state="
+ state + ", city=" + city + ", phone=" + phone + ", mobile=" + mobile + ", carrier=" + carrier
+ ", status=" + status + ", leftSide=" + leftSide + ", rightSide=" + rightSide + ", created=" + created
+ ", parentId=" + parentId + ", parentSide=" + parentSide + ", networkSide=" + networkSide
+ ", activated=" + activated + ", points=" + points + ", nickname=" + nickname + ", nis=" + nis
+ ", whatsapp=" + whatsapp + ", bank=" + bank + ", accountType=" + accountType + ", branchNumber="
+ branchNumber + ", branchDigit=" + branchDigit + ", accountNumber=" + accountNumber + ", accountDigit="
+ accountDigit + ", accountOwner=" + accountOwner + ", cpfAccountOwner=" + cpfAccountOwner
+ ", facebookID=" + facebookID + ", career=" + career + ", pb=" + pb + ", certID=" + certID
+ ", automaticRenovation=" + automaticRenovation + ", emailPagamento=" + emailPagamento
+ ", rightSideAccount=" + rightSideAccount + ", leftSideAccount=" + leftSideAccount
+ ", searchableBySignedInUser=" + searchableBySignedInUser + ", totalCandidatosAgente="
+ totalCandidatosAgente + ", totalAgentes=" + totalAgentes + ", totalAgentesBracoEsq="
+ totalAgentesBracoEsq + ", totalAgentesBracoDir=" + totalAgentesBracoDir + ", totalAnjos=" + totalAnjos
+ ", cfaCompleto=" + cfaCompleto + ", tickets=" + tickets + ", scores=" + scores + ", productsAccount="
+ productsAccount + ", trades=" + trades + "]";
}
}
And this is my select result( snapshot table is to big )
[
id=2111,
userId=99YWK,
fullname=PatrickRibeiroBraz,
email=null,
birthdate=null,
cpf=null,
rg=null,
address=null,
addressNumber=null,
complement=null,
cep=null,
state=null,
city=0,
phone=null,
mobile=null,
carrier=null,
status=null,
leftSide=0,
rightSide=0,
created=2018-06-1212: 09: 29.0,
parentId=999I2,
parentSide=null,
networkSide=null,
activated=null,
points=0.0,
nickname=null,
nis=null,
whatsapp=null,
bank=0,
accountType=null,
branchNumber=null,
branchDigit=null,
accountNumber=null,
accountDigit=null,
accountOwner=null,
cpfAccountOwner=null,
facebookID=null,
career=0.0,
pb=0.0,
certID=0,
automaticRenovation=null,
emailPagamento=null,
rightSideAccount=null,
leftSideAccount=null,
searchableBySignedInUser=false,
totalCandidatosAgente=0,
totalAgentes=0,
totalAgentesBracoEsq=0,
totalAgentesBracoDir=0,
totalAnjos=0,
cfaCompleto=false,
tickets={
IndirectList: notinstantiated
},
scores={
IndirectList: notinstantiated
},
productsAccount={
IndirectList: notinstantiated
},
trades={
IndirectList: notinstantiated
}
]
ID fullname status
2111 Patrick Ribeiro Braz C
Has anyone went through this before?
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.
This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
Java null pointer exceptions - don't understand why…
MOVIE.JAVA
package javaPractical.week3;
import javax.swing.*;
public class Movie {
// private attributes
private String title;
private String movieURL;
private String year;
private String genre;
private String actor;
// constructor
Movie(String t, String u, String y, String g, String a) {
this.title = t;
this.movieURL = u;
this.year = y;
this.genre = g;
this.actor = a;
}
// getters and setters
public void setTitle(String t) {
this.title = t;
}
public String getTitle() {
return this.title;
}
public void set_url(String a) {
this.movieURL = a;
}
public String get_url() {
return this.movieURL;
}
public void setYear(String y) {
this.year = y;
}
public String getYear() {
return this.year;
}
public void setGenre(String g) {
this.genre = g;
}
public String getGenre() {
return this.genre;
}
public void setActor(String a) {
this.actor = a;
}
public String getActor() {
return this.actor;
}
// output movie details
public String toString() {
return ("Title: " + this.title + "\nURL: " + this.movieURL + "\nYear: "
+ this.year + "\nGenre: " + this.genre + "\nActor: " + this.actor);
}
public static void main(String[] args) {
// testing Movie class
Movie Movie1 = new Movie("Spiderman", "www.", "2002", "Action",
"Tobey M");
JOptionPane.showMessageDialog(null, Movie1.toString());
// testing MovieList class
}
}
MOVIELIST.JAVA
package javaPractical.week3;
import javax.swing.*;
import java.util.ArrayList;
public class MovieList1 {
private static ArrayList<Movie> myFavouriteMovies = new ArrayList();
private static int NUM_OF_MOVIES = 10;
private int numberOfMovies = 0;
private int index = 0;
public MovieList1() {
this.myFavouriteMovies = null;
this.numberOfMovies = 0;
this.index = 0;
}
public int getNumberOfMovies() {
return this.myFavouriteMovies.size();
}
public boolean isEmpty() {
if (this.myFavouriteMovies.isEmpty()) {
return true;
} else
return false;
}
public static void main(String[] args) {
MovieList1 List = new MovieList1();
String titleADD;
String movieURLADD;
String yearADD;
String genreADD;
String actorADD;
titleADD = JOptionPane.showInputDialog(null, "Enter title:");
movieURLADD = JOptionPane.showInputDialog(null, "Enter URL:");
yearADD = JOptionPane.showInputDialog(null, "Enter year:");
genreADD = JOptionPane.showInputDialog(null, "Enter genre:");
actorADD = JOptionPane.showInputDialog(null, "Enter actor:");
Movie TempMovie = new Movie(titleADD, movieURLADD, yearADD, genreADD,
actorADD);
// crashes here
myFavouriteMovies.add(TempMovie);
}
}
You have defined static attribute private static ArrayList<Movie> myFavouriteMovies = new ArrayList();
But in the constructor you are assigning the null. After that you are invoking calls like myFavouriteMovies.size() which causes NullPointerException
public MovieList1() {
this.myFavouriteMovies = null;
this.numberOfMovies = 0;
this.index = 0;
}
Of course it crashes - you've set it to null.
Why on earth didn't you heed the perfectly good advice you received here?
Java null pointer exceptions - don't understand why
You're wasting everyone's time on a trivial question. I'm voting to close.
Try this - it's still heinous, but it runs:
package javaPractical.week3;
import javax.swing.*;
import java.util.ArrayList;
import java.util.List;
public class MovieList1
{
private static int NUM_OF_MOVIES = 10;
private List<Movie> myFavouriteMovies;
private int numberOfMovies = 0;
private int index = 0;
public MovieList1()
{
this.myFavouriteMovies = new ArrayList<Movie>();
this.numberOfMovies = 0;
this.index = 0;
}
public int getNumberOfMovies()
{
return this.myFavouriteMovies.size();
}
public boolean isEmpty()
{
return this.myFavouriteMovies.isEmpty();
}
public void add(Movie movie)
{
this.myFavouriteMovies.add(movie);
}
#Override
public String toString()
{
return "MovieList1{" +
"myFavouriteMovies=" + myFavouriteMovies +
'}';
}
public static void main(String[] args)
{
MovieList1 movieList = new MovieList1();
String titleADD;
String movieURLADD;
String yearADD;
String genreADD;
String actorADD;
titleADD = JOptionPane.showInputDialog(null, "Enter title:");
movieURLADD = JOptionPane.showInputDialog(null, "Enter URL:");
yearADD = JOptionPane.showInputDialog(null, "Enter year:");
genreADD = JOptionPane.showInputDialog(null, "Enter genre:");
actorADD = JOptionPane.showInputDialog(null, "Enter actor:");
Movie TempMovie = new Movie(titleADD, movieURLADD, yearADD, genreADD,
actorADD);
// crashes here
movieList.add(TempMovie);
System.out.println(movieList);
}
}
class Movie
{
private String title;
private String url;
private String year;
private String genre;
private String actor;
Movie(String title, String url, String year, String genre, String actor)
{
this.title = title;
this.url = url;
this.year = year;
this.genre = genre;
this.actor = actor;
}
#Override
public String toString()
{
return "Movie{" +
"title='" + title + '\'' +
", url='" + url + '\'' +
", year='" + year + '\'' +
", genre='" + genre + '\'' +
", actor='" + actor + '\'' +
'}';
}
}