Using default and non default constructors in my application - java

I'm new to java and have a question about default and non default constructors. My professor wants us to use the default constructor for creation of object BOOK1, and then use the non default constructor for BOOK2, BOOK3 and BOOK4. I know a constructor is used with the creation of an object, but I guess I don't understand how i'm supposed to differentiate between the two. My class code is as follows, where I have both a default and non default constructor:
import java.text.DecimalFormat;
public final class BOOKItem {
DecimalFormat intFormat = new DecimalFormat("000");
DecimalFormat doubleFormat = new DecimalFormat("$#,##0.00");
private int bookID;
private int numberInStock;
private double price;
private double totalValueOfStock;
private int code;
private String genre = "";
public BOOKItem() {
bookID = 0;
numberInStock = 0;
price = 0;
code = 0;
}
public BOOKItem(int newID, int newStock, double newPrice, int newCode) {
setID(newID);
setStock(newStock);
setCode(newCode);
setPrice(newPrice);
}
public void setStock (int newStock) {
if (newStock >= 1 && newStock <=5000) {
numberInStock = newStock;
}
else {
numberInStock = 0;
}
}
public void setCode (int newCode) {
if (newCode > 0) {
code = newCode;
}
}
public void setID (int newID) {
if (newID >=11 && newID <= 111111) {
bookID = newID;
}
else {
bookID = 0;
}
}
public void setPrice (double newPrice) {
if (newPrice >= 1.0 && newPrice <=150.0) {
price = newPrice;
}
else {
price = 0;
}
}
public int getID () {
return bookID;
}
public int getNumberInStock () {
return numberInStock;
}
public int getCode () {
return code;
}
public double getPrice () {
return price;
}
public double calcTotalValue () {
totalValueOfStock = numberInStock * price;
return totalValueOfStock;
}
public double getTotalValue () {
return totalValueOfStock;
}
public void display() {
switch (code)
{
case 1:
genre = "Romance";
break;
case 2:
genre = "Adventure";
break;
case 3:
genre = "Sci-Fi";
break;
case 4:
genre = "Mystery";
break;
}
System.out.println("Display:");
System.out.println("Book ID: " + bookID + " NumInStock: " + numberInStock + " Code: " + genre + " Price: " +
price + " TotalStockValue: " + calcTotalValue());
}
}
Here is my application that uses the constructors(sorry about the break in the class code, i dunno why its doing that):
import java.util.Scanner;
public class Project7 {
public static void main(String[] args) {
int bookID;
int numberInStock;
double price;
int code;
Scanner keyboard = new Scanner(System.in);
BOOKItem BOOK1, BOOK2, BOOK3, BOOK4;
BOOK1 = new BOOKItem();
BOOK2 = new BOOKItem();
BOOK3 = new BOOKItem();
BOOK4 = new BOOKItem();
System.out.println("Enter in a blank separated list: ID, number in stock, quality, price" +
"- use a BAD ID(<11 or >111111)");
bookID = keyboard.nextInt();
numberInStock = keyboard.nextInt();
code = keyboard.nextInt();
price = keyboard.nextDouble();
BOOK1.setID(bookID);
BOOK1.setStock(numberInStock);
BOOK1.setCode(code);
BOOK1.setPrice(price);
BOOK1.display();
System.out.println("Enter in a blank separated list: ID, number in stock, quality, price" +
"- use a BAD STOCK(>5000)");
bookID = keyboard.nextInt();
numberInStock = keyboard.nextInt();
code = keyboard.nextInt();
price = keyboard.nextDouble();
BOOK2.setID(bookID);
BOOK2.setStock(numberInStock);
BOOK2.setCode(code);
BOOK2.setPrice(price);
BOOK2.display();
System.out.println("Enter in a blank separated list: ID, number in stock, quality, price" +
"- use a BAD PRICE(>150.0)");
bookID = keyboard.nextInt();
numberInStock = keyboard.nextInt();
code = keyboard.nextInt();
price = keyboard.nextDouble();
BOOK3.setID(bookID);
BOOK3.setStock(numberInStock);
BOOK3.setCode(code);
BOOK3.setPrice(price);
BOOK3.display();
System.out.println("Enter in a blank separated list: ID, number in stock, quality, price" +
"- use ALL GOOD DATA");
bookID = keyboard.nextInt();
numberInStock = keyboard.nextInt();
code = keyboard.nextInt();
price = keyboard.nextDouble();
BOOK4.setID(bookID);
BOOK4.setStock(numberInStock);
BOOK4.setCode(code);
BOOK4.setPrice(price);
BOOK4.display();
}
}
Am I doing something incorrect with the creation of my objects? How do I use the non default constructor for BOOK2, BOOK3 and BOOK4? I created it, but perhaps i'm using it incorrectly. Any feedback would be greatly appreciated.

When you use
BOOK1 = new BOOKItem();
You are calling the default constructor (Construction without having any arguments)
After taking user input you would call the Non Default Constructor
bookID = keyboard.nextInt();
numberInStock = keyboard.nextInt();
code = keyboard.nextInt();
price = keyboard.nextDouble();
BOOK2 = new BOOKItem(bookID, numberInStock, price, code);
Use the above code to use the Parameterized Constructor (Non Default constructor)
This is called constructor overloading.
So for the objects you want to assign default values you call the default constructor
For the object you have information available with variables you sent them in the constructor that you have defined with parameters, To assign that value

Related

dont shows the values in the array - Java

i'm doing an exercise where i have that to store objects in the array, the problem is when i'm going to print the objects of the array, dont shows the values of type String, the output is:
AFGH
3
5
2
3
5
5
1
2
5
7
my code is:
public static void main(String[] args){
Bill[] billsList = new Bill[5];
Scanner scanner = new Scanner(System.in);
String productCode = " ";
int kilos = 0;
int price = 0;
for(int i = 0; i < billsList.length; i++) {
System.out.println("Digit the code of the product: ");
productCode = scanner.nextLine();
scanner.nextLine();
System.out.println("Digit the kilos sold: ");
kilos = scanner.nextInt();
System.out.println("Digit the price: ");
price = scanner.nextInt();
Bill bills = new Bill(productCode,kilos,price);
billsList[i] = bills;
}
for(int i = 0; i < billsList.length; i++) {
System.out.println(billsList[i]);
System.out.println(billsList[i]);
System.out.println(billsList[i]);
}
}
the code of the class Bill is this:
public class Bill {
private String productCode;
private int kilosSold;
private int price;
public Bill(String productCode,int kilosSold,int price) {
this.productCode = productCode;
this.kilosSold = kilosSold;
this.price = price;
}
}
In Bill class, you have to override toString() method of the Object class.
Somewhat like:
#Override
public String toString() {
return "Product : " + productCode + " kilosold : " + kilosSold + "price : " + price;
}
or optionally you can use the #ToString of the lombok to avoid this boilerplate code.
Also, you can change your data members of class to final.
Somewhat like:
private final String productCode;
private final int kilosSold;
private final int price;
remove the nextLine and it would print fine:
System.out.println("Digit the code of the product: ");
productCode = scanner.next();
System.out.println("Digit the kilos sold: ");
kilos = scanner.nextInt();
in addition, you should override the toString method like what was answered above.
If you want to print a complete object array, and all the attributes you should use the Arrays class method "toString". If you only want one of the attributes, for example: the product code, you should use a getter method. Investigate about getter and setter methods, it will help you a lot.
public static void main(String[] args){
Bill[] billsList = new Bill[5];
Scanner scanner = new Scanner(System.in);
String productCode = " ";
int kilos = 0;
int price = 0;
for(int i = 0; i < billsList.length; i++) {
System.out.println("Digit the code of the product: ");
productCode = scanner.nextLine();
System.out.println("Digit the kilos sold: ");
kilos = scanner.nextInt();
System.out.println("Digit the price: ");
price = scanner.nextInt();
Bill bills = new Bill(productCode,kilos,price);
billsList[i] = bills;
}
System.out.println(Arrays.toString(billsList));
}

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

Copy Constructor Test not Working (Java)

I'm working on CS homework and have run into a problem. The end of the homework asks about using a copy constructor. The goal is to "make one Payroll object, instantiate it, make a second one, then print them both. Then, change values in the second Payroll object, and show that the changed values only appear in one and not both (that is, print out the original and the copy with slightly changed values)." I tried changing the values in the second Payroll object, but it also changes it in the first. I've listed my code below:
import java.util.Random;
public class Payroll {
private int[] employeeId;
private int[] hours;
private double[] payRate;
public Payroll(){
this.employeeId = new int[0];
this.hours = new int[0];
this.payRate = new double[0];
}
public Payroll(Payroll obj){
this.employeeId = obj.employeeId;
this.hours = obj.hours;
this.payRate = obj.payRate;
}
public Payroll(int i){
this.employeeId = new int[i];
this.hours = new int[i];
this.payRate = new double[i];
}
public int getEmployeeIdAt(int index){
return employeeId[index];
}
public int getHoursAt(int index){
return hours[index];
}
public double getPayRateAt(int index){
return payRate[index];
}
public double getGrossPay(int index){
double grossPay = hours[index] * payRate[index];
grossPay = Math.round(grossPay * 100);
return grossPay/100;
}
public void setEmployeeIdAt(int index, int id){
this.employeeId[index] = id;
}
public void setHoursAt(int index, int hrs){
this.hours[index] = hrs;
}
public void setPayRateAt(int index, double pr){
this.payRate[index] = pr;
}
public void setHoursAt(int i){
Random rand = new Random();
int randHours = rand.nextInt((50 - 15) + 1) + 15;
this.hours[i] = randHours;
}
}
import java.util.Scanner;
public class PayrollDriver {
public static void main(String[] args) {
Payroll pr = new Payroll(5);
Scanner scan = new Scanner(System.in);
int empID = 1001;
for(int i = 0; i < 5; i++){
pr.setEmployeeIdAt(i, empID);
empID++;
}
for(int i = 0; i < 5; i++){
System.out.println("Enter the hourly pay rate for employee number " + pr.getEmployeeIdAt(i) + ": ");
double payRate = scan.nextDouble();
if(payRate < 7.50){
do{
System.out.println("ERROR: Enter 7.50 or greater for pay rate: ");
payRate = scan.nextDouble();
} while(payRate < 7.50);
}
pr.setPayRateAt(i, payRate);
pr.setHoursAt(i);
}
System.out.println("PAYROLL DATA");
System.out.println("======================");
for(int i = 0; i < 5; i++){
System.out.println("Employee ID: " + pr.getEmployeeIdAt(i) + " Hours: " + pr.getHoursAt(i) + " Rate: " + pr.getPayRateAt(i) +
" Gross Pay: $" + pr.getGrossPay(i));
}
System.out.println("Would you like to run the Copy Constructor Test? Enter 'y' (lowercase) if yes, enter any other letter if no: ");
char copyTestVerify = scan.next().charAt(0);
if(copyTestVerify == 'y'){
CopyConstructorTest ct = new CopyConstructorTest();
ct.CopyTest();
}
scan.close();
}
}
The following is my CopyConstructorTest class, the one that tests whether or not the copy constructor will change the original object's values:
public class CopyConstructorTest {
public void CopyTest(){
Payroll pay = new Payroll(5);
pay.setEmployeeIdAt(0, 1001);
Payroll payCopy = new Payroll(pay);
System.out.println("Original: " + pay.getEmployeeIdAt(0));
System.out.println("Copy: " + payCopy.getEmployeeIdAt(0));
payCopy.setEmployeeIdAt(0, 5000);
System.out.println("Original after changes: " + pay.getEmployeeIdAt(0));
System.out.println("Copy after changes: " + payCopy.getEmployeeIdAt(0));
}
}
I'm not positive on what I'm doing wrong. Any help or guidance is much appreciated.
You are just copying the references to the arrays, not the actual data. Therefore whenever you change the data in one of your objects, the changes are seen in both, since they point to the same array.
The easiest way to copy the data is probably using System.arraycopy():
public Payroll(Payroll obj) {
this.employeeId = new int[obj.employeeId.length];
System.arraycopy(obj.employeeId, 0, this.employeeId, 0, obj.employeeId.length);
...

Constructor error with encapsulation

I have my code in 3 different files using encapsulation (Data hiding) and i have 1 problem at the very end of my code in my if and else statement (very bottom) when trying to call the classes from the other 2 documents. I will put the code in 1st document to 3rd document. Any suggestions on what I did wrong?
// FIRST DOCUMENT
public class CollegeCourse { //class name
//variables
String deptName;
int courseNum;
int credits = 3;
double fee;
//constructor
public CollegeCourse(String department, int course, int Credits) {
deptName = department;
courseNum = course;
credits = Credits;
fee = credits * 120;
}
//getters setters
public String getdepartment() {
return deptName;
}
public String setdepartment(String dept) {
return dept = deptName;
}
public int getcourse() {
return courseNum;
}
public int setcourse(int c) {
return c = courseNum;
}
public int getCredits() {
return credits;
}
public int setCredits(int cred) {
return cred = credits;
}
public void display()
{
System.out.println("Department: " + deptName);
System.out.println("Course Number: " + courseNum);
System.out.println("Credits: " + credits);
System.out.println("Fee: $" + fee);
}
}
//SECOND DOCUMENT
public class LabCourse extends CollegeCourse { //polymorphism extending CollegeCourse class into LabCourse class.
//constructor
public LabCourse(String department, int course, int Credits){
//add 50 dollars to the fee
super(department, course, Credits);
fee = fee + 50;
}
//display the course
public void display(){
System.out.print("This course is a lab course" + fee);
System.out.println("Department: " + deptName);
System.out.println("Course Number: " + courseNum);
System.out.println("Credits: " + credits);
System.out.println("Fee: $" + fee);
}
}
//THIRD DOCUMENT MAIN HEADER
import java.util.Scanner;
public class UseCourse {
public static void main(String[] args){
String s, c, cd;
Scanner input = new Scanner(System.in);
System.out.print("Enter: BIO, CHEM, ENG, MATH: ");
s = input.nextLine();
System.out.print("What is the course number: ");
c = input.nextLine();
System.out.print("How many credits: ");
cd = input.nextLine();
if(s.equals ("BIO") || s.equals ("CHEM")){
LabCourse lc = new LabCourse(department, course, Credits); //here is my problem, it can't find the CollegeCourse class department, course,//and credits...
lc.display();
}
else {
CollegeCourse cc = new CollegeCourse(department, course, Credits); //here is my problem, it can't find the CollegeCourse class department, course,//and credits...
cc.display();
}
}
}
Here is the error that i'm getting.
UseCourse.java:24: error: cannot find symbol
LabCourse lc = new LabCourse(department, course, Credits);
^
And it repeats for each error "department, course, Credits"
UseCourse.java:29: error: cannot find symbol
CollegeCourse cc = new CollegeCourse(department, course, Credits);
^
Your parameters in your constructor call are all wrong. Neither department, course or Credits are defined, so you would need to use s, c and cd instead, as those are the variables you're using for your input.
Furthermore, you need to read c and cd as integers and pass those to your constructor as follows:
System.out.print("What is the course number: ");
int c = input.nextInt();
System.out.print("How many credits: ");
int cd = input.nextInt();
// ...
LabCourse lc = new LabCourse(s, c, cd);

Need to call a method from a specific class

I need to call the method getAmount() from the Service class only. I do not want to add the values of the Purchaser class. Is there a way I can call the method explicitly from the Service class? I have put a ** where I am referring to.
package prog24178.assignment;
import java.util.Scanner;
public class Assignment3 {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
final int MAX = 99999; // Max array size.
Customer [] cust = new Customer[MAX];
int choice = 0;
int cnt = 0;
double total = 0;
//loop to choose customer type and create a new object.
for(cnt=0; cnt < MAX && (choice == 1 || choice ==2 || choice == 0); cnt++){
System.out.println("For a Service customer type 1, for a Purchaser type 2, to terminate the program press any number besides 1 or 2");
choice = s.nextInt();
switch (choice){
case 1:
cust [cnt] = new Service();
break;
case 2:
cust [cnt] = new Purchaser();
break;
default:
break;
}
}
//loop to print the entries
for(int i=0; i < cnt; i++){
if(cust[i]!= null)
cust[i].showData();
}
//loop to print the total for the service objects.**THIS IS LOOP I AM //REFFERING TO
for(int i=0; i < cnt; i++ ){
if(cust[i]!= null)
total = cust[i].getAmounts() + total;
}
System.out.println("Monthly invoice total: " + total);
s.close();
}
}
interface Functions {
public void getData();
public void showData();
public double getAmounts();
}
abstract class Customer implements Functions {
protected String name;
}
class Purchaser extends Customer {
protected double payment;
public Purchaser(){
getData();
}
public void getData() {
Scanner s = new Scanner(System.in);
System.out.println("Enter the name of the customer");
name = s.nextLine();
System.out.println("Enter payment amount: ");
payment = s.nextDouble();
}
public void showData() {
System.out.printf("Customer name: %s Payment amount is: %.2f\n",name,payment);
}
//**I DO NOT WANT TO CALL THIS METHOD
public double getAmounts(){
return this.payment;
}
}
class Service extends Customer {
protected String date;
public double amount;
public Service () {
getData();
}
public void getData() {
Scanner s = new Scanner(System.in);
System.out.println("Enter the name of the customer");
name = s.nextLine();
System.out.println("Enter date of Service: ");
date = s.nextLine();
System.out.println("Enter the cost of Service: ");
amount = s.nextDouble();
}
public void showData() {
System.out.printf("Customer name: %s The date is: %s, the Amount owed is: %.2f\n",name, date, amount);
}
//**THIS IS THE METHOD I NEED TO CALL
public double getAmounts(){
return this.amount;
}
}
Check your customer for type:
if (cust[i] instanceof Service) {
total = cust[i].getAmounts() + total;
}
That takes care of the null check automatically as well.

Categories