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.
Related
Let's say I have this class:
public class Customer()
{
private double discountamount;
private double totalPurchase;
public Customer(double tot)
{
this.totalPurchases = tot;
if (tot > 2000.00){setDiscountAmount(0.25);}
else if (tot >= 1000.00){setDiscountAmount(0.15);}
else if (tot >= 500.00){setDiscountAmount(0.10);}
}
public double getDiscountAmount(){return discountAmount;}
public double getTotalPurchases(){return totalPurchases;}
public void setDiscountAmount(double newDiscountAmount){discountAmount = newDiscountAmount;}
public void setTotalPurchases(double newTotalPurchases){totalPurchases = newTotalPurchases;}
}
And I want to change the value of the total purchase without creating a new object.
import java.util.Scanner;
public class Discounts
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
double totalPurchase;
System.out.print("Enter amount customer has spent: ");
totalPurchase = input.nextDouble();
Customer customer = new Customer(totalPurchase);
System.out.print("\nHas the customer returned with more purchases? ");
boolean loop = input.nextLine().equalsIgnoreCase("yes");
if (loop){
System.out.print("How many times? ");
int x = input.nextInt();
for (int i = 0; i < x; i++) {
// Accumulate
System.out.print("Enter amount customer has spent: ");
totalPurchase += input.nextDouble() * customer.discountAmount;
customer.setTotalPurchases(totalPurchase);
}
System.out.println("Customer Discount Amount: " + customer.discountAmount);
System.out.println("Customer Total Purchase Amount: " + customer.totalPurchases);
}
}
}
But when I print the new discount amount, it remains unchanged. So where am I going wrong and what can I do?
That's because discountAmount is only set in the constructor, which happens only once an object is instantiated. Instead, you should move the if-statement in your constructor to the setTotalPurchases, like so:
public class Customer{
private double discountamount;
private double totalPurchase;
public Customer(double tot){
this.setTotalPurchases(tot);
}
public double getDiscountAmount(){return discountAmount;}
public double getTotalPurchases(){return totalPurchases;}
public void setDiscountAmount(double newDiscountAmount){discountAmount = newDiscountAmount;}
public void setTotalPurchases(double newTotalPurchases){
totalPurchases = newTotalPurchases;
if (tot > 2000.00){
setDiscountAmount(0.25);
}else if (tot >= 1000.00){
setDiscountAmount(0.15);
}else if (tot >= 500.00){
setDiscountAmount(0.10);
}
}
}
You can move the logic for changing the discount amount to a setter:
public Customer(double tot) {
setTotalPurchases(tot);
}
public void setTotalPurchases(double newTotalPurchases){
totalPurchases = newTotalPurchases;
if (newTotalPurchases > 2000.00) {
setDiscountAmount(0.25);
} else if (newTotalPurchases >= 1000.00) {
setDiscountAmount(0.15);
} else if (newTotalPurchases >= 500.00) {
setDiscountAmount(0.10);
}
}
so with the program, the user inputs data for the object in one file Inv.java and then that information is stored in Product.java and in store.java. from store.java there is an arrayList which holds the information but when 2 items are attempted to be put in, the second object writes over the first, how can I fix this and how can I be able to call the objects back in Inv.java
code for Inv.java
import java.util.Scanner;
import java.util.*;
import java.util.ArrayList;
public class Inv
{
public static void main(String args[])
{
Scanner console = new Scanner(System.in);
String str;
char c;
int n=0;
System.out.println(" INVENTORY MANAGEMENT SYSTEM");
System.out.println("===============================================");
System.out.println("1. ADD PRODUCT DATA");
System.out.println("2. VIEW PRODUCT DATA");
System.out.println("3. VIEW REPRLENISHMENT STRATEGY");
System.out.println("===============================================");
System.out.println("4. EXIT PROGRAM");
while(n!=4)// Exits the program when 4 is pressed
{
System.out.print("\n Please enter option 1-4 to continue...: ");
n = Integer.parseInt(System.console().readLine());
// Reads user input and takes them to selected code.
if (n>4||n<1)
{
System.out.print("Invalid input, please try again...");
continue;
}
if (n==1)// Takes to option 1 or addItem()
{
str="y";
while(str.equals("y")||str.equals("Y"))
{
Inv.addItem();
System.out.print("Would you like to enter another product ? (Y or N) : ");
str = console.next();
}
continue;
}
if (n==2)// Takes to option 2 or prodData
{
str="y";
while(str.equals("y")||str.equals("Y"))
{
Inv.prodData();
System.out.println("\n***************************************************\n");
System.out.print("Stay viewing this page? (Y or N) ");
str = console.next();
}
continue;
}
else
if (n==3)// Takes to option 3 or replenStrat
{
System.out.print("View Replenishment Strategy.");
continue;
}
}
System.out.print("\nThank you for using this inventory management software.\n");
System.out.print("Developed by Xavier Edwards");
System.out.println("\n***************************************************\n");
}
// Global variables so that any class can call it and use the information in it
public static Product product;
public static Store store;
// Where the user inputs the data for the item
public static void addItem ()
{
Scanner console = new Scanner(System.in);
product = new Product();// initiates the product and store to being empty.
store = new Store();
String desc, id, str="";
double price = 0, sUpPrice = 0, unitCost = 0, inventoryCost = 0;
int stock = 0, demand = 0;
System.out.print("Please enter product description between 3 to 10 characters...: ");
desc = console.next();
desc = desc.toLowerCase();
product.setName(desc);
if ((desc.length() < 3 || desc.length() > 10))
{
System.out.println("\nThis Input is incorrect. Please make description between 3 to 10 characters.\n");
System.out.println("Try again with different input. ");
System.out.println("\n*****************************************\n");
Inv.addItem();
}
System.out.print("Please enter price in $ : ");
price = console.nextDouble();
product.setPrice(price);
if (price < 0)
{
System.out.println("\nThis Input is incorrect. Please make sure attributes are positve numbers\n");
System.out.println("Because of incorrect input, program will restart. ");
System.out.println("\n*****************************************\n");
Inv.addItem();
}
System.out.print("Please enter set up price. $ : ");
sUpPrice = console.nextDouble();
product.setsUpPrice(sUpPrice);
if (sUpPrice < 0)
{
System.out.println("\nThis Input is incorrect. Please make sure attributes are positve numbers\n");
System.out.println("Because of incorrect input, program will restart. ");
System.out.println("\n*****************************************\n");
Inv.addItem();
}
System.out.print("Please enter unit- cost. $ : ");
unitCost = console.nextDouble();
product.setunitCost(unitCost);
if (unitCost < 0)
{
System.out.println("\nThis Input is incorrect. Please make sure attributes are positve numbers\n");
System.out.println("Because of incorrect input, program will restart. ");
System.out.println("\n*****************************************\n");
Inv.addItem();
}
System.out.print("Please enter the inventory cost. $ : ");
inventoryCost = console.nextDouble();
product.setinvCost(inventoryCost);
if (inventoryCost < 0)
{
System.out.println("\nThis Input is incorrect. Please make sure attributes are positve numbers\n");
System.out.println("Because of incorrect input, program will restart. ");
System.out.println("\n*****************************************\n");
Inv.addItem();
}
System.out.print("Please enter the amount in stock : ");
stock = console.nextInt();
product.setstock(stock);
if (stock < 0)
{
System.out.println("\nThis Input is incorrect. Please make sure attributes are positve numbers\n");
System.out.println("Because of incorrect input, program will restart. ");
System.out.println("\n*****************************************\n");
Inv.addItem();
}
System.out.print("Please enter the demand of the product : ");
demand = console.nextInt();
product.setdRate(demand);
if (demand < 0)
{
System.out.println("\nThis Input is incorrect. Please make sure attributes are positve numbers\n");
System.out.println("Because of incorrect input, program will restart. ");
System.out.println("\n*****************************************\n");
Inv.addItem();
}
System.out.println("\n*****************************************\n");
System.out.print(desc +" Product was added successfully ");
System.out.println("\n*****************************************\n");
// stores the item in the array
store.add(product);
}
// Where the product information is being returned to the user
public static void prodData()
{
Scanner console = new Scanner(System.in);
String pOption, str;
System.out.print("\nEnter product description to view the data...\n");
pOption = console.next();//
product = store.getProduct(pOption); //Checks to see if the item is created
// so that data can be displayed
if (product != null){
System.out.println("Product description : "+product.getName());
System.out.println("Price : $ "+product.getPrice());
System.out.println("Set-up Price : $ "+product.getsUpPrice());
System.out.println("Unit Cost : $ "+product.getunitCost());
System.out.println("Inventory Cost : $ "+product.getinvCost());
System.out.println("Amount of Stock : "+product.getstock());
System.out.println("Amount of Stock : "+product.getdRate());
}else{
System.out.println("\nThere is no information on this product.\n");
System.out.println("\nWould you like to try again? (Y or N) \n");
str = console.next();
Inv.prodData();
}
}
}
code for Product.java
public class Product
{
public String name;
public double price, sUpPrice, unitCost, invCost;
public int stock, demand;
public Product()
{
name = "";
price = 0;
sUpPrice = 0;
unitCost = 0;
invCost = 0;
stock = 0;
demand = 0;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return this.name;
}
public void setPrice(double price) {
this.price = price;
}
public double getPrice() {
return this.price;
}
public void setsUpPrice(double sUpPrice) {
this.sUpPrice = sUpPrice;
}
public double getsUpPrice() {
return this.sUpPrice;
}
public void setunitCost(double unitCost) {
this.unitCost = unitCost;
}
public double getunitCost() {
return this.unitCost;
}
public void setinvCost(double invCost) {
this.invCost = invCost;
}
public double getinvCost() {
return this.invCost;
}
public void setstock(int stock) {
this.stock = stock;
}
public int getstock() {
return this.stock;
}
public void setdRate(int demand) {
this.demand = demand;
}
public int getdRate() {
return this.demand;
}
}
code for store.java
import java.util.*;
import java.util.ArrayList;
public class Store{
public ArrayList <Product> ProductList = new ArrayList<Product> ();
public Store()
{
//ArrayList = "";
}
public void add(Product product)
{
ProductList.add(product);
}
public Product getProduct(String prodName) {
for (int i = 0; i < ProductList.size(); i++) {
if (ProductList.get(i).getName().equals(prodName)) {
return ProductList.get(i);
}
}
return null;
}
}
any help be with appreciated.
Problem is in Inv.addItem() method where you are instantiating variable store every time you invoke it.
store = new Store();
Looking at your code, you should instantiate it in Inv:
public static Store store = new Store();
I've got a class, "vehicle" which should allow the array to be saved with the information input by the user but when I try and get the method to accept the data with the counter giving each data entry a unique number it doesn't accept anything past the [ on vehicle vehiclearray[totalcount] = new vehiclearray(count,licence,date,value,colour); I'm relatively new to java and this problem has stumped me, any help would be appreciated.
This is the whole code, the problem is under submenu1.
import java.util.Scanner;
class main
{
public static void main(String[] args)
{
Scanner input = new Scanner (System.in);
int option = menu();
int totalcount = submenu1.totalcount;
int carcount = submenu1.carcount;
int bikecount = submenu1.bikecount;
vehicle vehiclearray[] = new vehiclearray[100];
if (option == 1)
submenu1(vehiclearray);
else if (option ==2)
submenu2(totalcount, vehiclearray);
else if (option ==3)
submenu3(totalcount, carcount, bikecount,museumbike, museumcar);
else if (option ==4)
submenu4(carcount, museumcar);
else if (option ==5)
submenu5(bikecount, museumbike);
else if (option ==6)
System.out.println("Thank you for using this program");
else
System.out.println("Invalid selection, please try again.");
}
}
class menusystem
{
public static int menu()
{
Scanner input = new Scanner (System.in);
int option = 0;
System.out.println("Please select an option");
System.out.println("=======================");
System.out.println("1. Add a vehicle to the collection");
System.out.println("2. List vehices manufactured by a specifit year");
System.out.println("3. List all vehcles of a certain engine size or more");
System.out.println("4. list all cars");
System.out.println("5. List all bikes");
System.out.println("6. Exit");
option = input.nextInt();
return option;
}
public static int submenu1(vehicle vehiclearray[])
{
Scanner input = new Scanner (System.in);
String suboption1;
int totalcount = carcount = bikecount = 1;
System.out.println("Is the vehicle a car or a bike? (exit to close)");
suboption1 = input.next();
while(!suboption1.equalsIgnoreCase("exit"))
{
if (suboption1.equalsIgnoreCase("car"))
{
vehicle.id=count;
System.out.println("Please enter the licence, manufacture year, car value and colour of the car");
vehicle vehiclearray[totalcount] = new vehiclearray(count,licence,date,value,colour);
System.out.println("Please enter the number of doors, number of seats, engine type (petrol or deisol) and engine size in litres");
museumcar museumcar[carcount] = new museumcar(cardoors,seats,enginetype,carenginesize);
totalcount++;
carcount++;
}
else if (suboption1.equalsIgnoreCase("bike"))
{
System.out.println("Please enter the licence, manufacture year, car value and colour of the bike");
vehicle vehiclearray[totalcount] = new vehiclearray(licence,date,value,colour);
vehicle.id=count;
System.out.println("Please enter the bike type (sports, tourer or trials) and engine size in cc");
museumbike museumbike[bikecount] = new museumbike(type,bikeenginesize);
totalcount++;
bikecount++;
}
else
System.out.println("Please enter a valid entry.");
System.out.println("Is the vehicle a car or a bike? (exit to close)");
suboption1 = input.next();
return bikecount;
return carcount;
return totalcount;
}
}
public static void submenu2(int totalcount, vehicle vehiclearray[])
{
Scanner input = new Scanner (System.in);
int desiredyear = 0;
int count = 1;
System.out.println("What vehicle manufacture date do you want to see?");
desiredyear = input.nextInt();
for (count = 1; count <= totalcount; count++)
{
if (vehiclearray[totalcount].getdate == desiredyear)
System.out.println(vehiclearray[totalcount] +" id : "+ vehiclearray[totalcount].getlicence(), +" licence : "+ vehiclearray[totalcount].getdate(), +" date : "+ vehiclearray[totalcount].getvalue(), +" value : "+ vehiclearray[totalcount].getcolour() +" colour:");
else
System.out.println(vehiclearray[totalcount] +" does not match the desired manufacture year");
}
}
public static void submenu3(int totalcount, int carcount, int bikecount, museumbike museumbike[], museumcar museumcar[])
{
Scanner input = new Scanner (System.in);
double desiredsize = 0;
int count = 1;
System.out.println("What vehicle size or more do you want to see?");
desiredsize = input.nextDouble();
for (count = 1; count <= totalcount; count++)
{
if (desiredsize >=0 && desiredsize <=100)
{
if (museumcar[carcount].getcarenginesize >= desiredsize)
System.out.println(museumcar[carcount].getcardoors(), +(" doors : ")+ museumcar[carcount].getseats(), +(" seats : ")+ museumcar[carcount].getenginetype(), +(" : ")+ museumcar[carcount].getcarenginesize() +("ltrs"));
else
System.out.println("This car has a lower engine size then the desiredsize");
}
else if (desiredsize >=100)
System.out.println(museumbike[bikecount].gettype(), +(" : ")+ museumbike[bikecount].getbikeenginesize() +("cc"));
}
}
public static void submenu4(int carcount, museumcar museumcar[])
{
int count = 1;
for (count = 1; count <= museumcar[carcount]; count++)
{
System.out.println(museumcar[carcount].getcardoors(), +(" doors : ")+ museumcar[carcount].getseats(), +(" seats : ")+ museumcar[carcount].getenginetype(), +(" : ")+ museumcar[carcount].getcarenginesize() +("ltrs"));
}
}
public static void submenu5(int bikecount, museumbike museumbike[])
{
int count = 1;
for (count = 1; count <= museumbike[bikecount]; count++)
{
System.out.println(("bike id:")+ museumbike[bikecount].gettype(), +(" : ")+ museumbike[bikecount].getbikeenginesize() +("cc"));
}
}
}
class vehicle
{
private int carid;
private String licence;
private int date;
private Double value;
private String colour;
vehicle (int i,String l, int d, double v, String c)
{
id = i;
licence = l;
date = d;
value = v;
colour = c;
}
int getid()
{
return id;
}
String getlicence()
{
return licence;
}
int getdate()
{
return date;
}
Double getvalue()
{
return value;
}
String getcolour()
{
return colour;
}
}
class museumcar extends vehicle
{
private int cardoors;
private int seats;
private String enginetype;
private Double carenginesize;
museumcar (int cd, int s, String et, Double ces)
{
super (i, l, d, v, c);
cardoors = cd;
seats = s;
enginetype = et;
carenginesize = es;
}
int getcardoors()
{
return cardoors;
}
int getseats()
{
return seats;
}
String getenginetype()
{
return enginetype;
}
Double getcarenginesize()
{
return carenginesize;
}
}
class museumbike extends vehicle
{
private String type;
private Double bikeenginesize;
museumbike (String t, Double bes)
{
super (i, l, d, v, c);
type = t;
bikeenginesize = bes;
}
String gettype()
{
return type;
}
Double getbikeenginesize()
{
return bikeenginesize;
}
}
There is no vehiclearray class and so you can't do new vehiclearray[...], but instead should do new vehicle[...].
So for example, this line of code is not legal:
vehicle vehiclearray[] = new vehiclearray[100];
but this is:
vehicle vehiclearray[] = new vehicle[100];
In general I think that most of declare our variable with the array brackets on the class and not on the variable:
vehicle[] vehiclearray = new vehicle[100];
Although your way is legal (if you created the correct array object declaration that is).
Additional Notes:
Your class names should start with a capital letter so as to comply with Java naming conventions so that others (us!) can better understand your code.
If you have a question and your code doesn't compile, you should post any and all full compiler error messages with your question and also indicate which line(s) in your code cause the errors.
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
I am working on a simple program for my intro to Object Oriented programing class, where I have 3 classes: Account, ATM and the main/Runner class.
I am experiencing a null pointer exception error in the constructor of the ATM class when I am trying to initialize the array of Accounts using a loop. I am new to Java so I don't really know what happens.
Here is the code:
import java.util.Date;
public class Account {
private int account_id;
private double account_balance;
private static double annual_interest_rate;
private Date date_Created;
Account(){
account_id = 0;
account_balance=0;
annual_interest_rate = 0;
date_Created = new Date();
}
Account(int account_id_in,
double account_balance_in, double annual_interest_rate_in) {
account_id = account_id_in;
account_balance = account_balance_in;
annual_interest_rate = annual_interest_rate_in;
date_Created = new Date();
}
int get_account_id(){
return account_id;
}
double get_account_balance(){
return account_balance;
}
double get_annual_interest_rate(){
return annual_interest_rate;
}
Date get_date_created(){
return date_Created;
}
void set_account_id(int account_id_in){
account_id = account_id_in;
}
void set_account_balance(double account_balance_in){
account_balance = account_balance_in;
}
void set_annual_interest_rate(double annual_interest_rate_in){
annual_interest_rate = annual_interest_rate_in;
}
double get_monthly_interest_rate(){
return annual_interest_rate/12;
}
double get_monthly_interest(){
return (account_balance * get_monthly_interest_rate())/100;
}
void perform_deposit(double deposit_in){
account_balance += deposit_in;
}
void perform_withdraw(double withdraw_amount){
account_balance -= withdraw_amount;
}
}
public class ATM {
private Account[] acct = new Account [10];
public ATM(){
//acct = new Account[10];
for(int i = 0; i<10 ; i++){
acct[i].set_account_id(i+1);
acct[i].set_account_balance(100); // here iam getting an error.
}
//you must set their ids to values as specified in the assignment
} //these are the teacher's comments and instructions.
public void displayMenu(){
System.out.println("ATM Menu:");
System.out.println("\tenter 1 for viewing the current balance");
System.out.println("\tenter 2 for withdrawing money");
System.out.println("\tenter 3 for for depositing money");
System.out.println("\tenter 4 for exiting the main menu");
}
public boolean checkID(int id){
for(int i = 0; i<10 ; i++){
if(acct[i].get_account_id() == id){
return true;
}
}
return false;
}
public double checkBalance(int idToSearch){
int indexOfAccountToReturn = 0;
for(int i = 0; i<10; i++){
if(acct[i].get_account_id() == idToSearch){
indexOfAccountToReturn = i;
break;
}
}
return acct[indexOfAccountToReturn].get_account_balance();
}
public void withdrawFunds(int id, double amount){
for(int i=0; i<10; i++){
if(acct[i].get_account_id() == id){
acct[i].perform_withdraw(amount);
break;
}
}
}
public void depositFunds(int id, double amount){
for(int i=0; i<10; i++){
if(acct[i].get_account_id() == id){
acct[i].perform_deposit(amount);
break;
}
}
}
}
import java.util.Scanner;
import javax.swing.JOptionPane;
public class Banking_Finance_Main {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
ATM atm = new ATM();
Scanner input = new Scanner(System.in);
do{
System.out.println("Account ID?");
int id = input.nextInt();
while(!(atm.checkID(id))){
String entry =
JOptionPane.showInputDialog("Incorrect Input");
id = Integer.parseInt(entry);
}
//prevent user to proceed without the correct id; use checkID method and store appropriately
do{
atm.displayMenu();
System.out.println("Your choice?");
int choice = input.nextInt();
while((choice >4) || (choice <1)){
String entry = JOptionPane.showInputDialog("Incorrect Imput");
choice = Integer.parseInt(entry);
}
//prevent user to proceed without the correct choice 1-4;
if(choice==1){
System.out.println("Enter the Account id to check the balance: ");
int idToSearch = input.nextInt();
System.out.println("The balance in this ACccount is: $" + atm.checkBalance(idToSearch));
}else if(choice==2){
System.out.println("Enter the Account id to perform withdrawal: ");
int idToSearch = input.nextInt();
System.out.println("Enter the amount to be withdrawn: ");
double amountToWithdraw = input.nextDouble();
atm.withdrawFunds(idToSearch, amountToWithdraw);
}else if(choice==3){
System.out.println("Enter the Account id to perform deposit: ");
int idToSearch = input.nextInt();
System.out.println("Enter the amount to be deposited: ");
double amountToDeposit = input.nextDouble();
atm.depositFunds(idToSearch, amountToDeposit);
}else{
break;
}
}while(true);
}while(true);
}
}
I am sorry if I am using this site inappropriately, this is my first question here so bear with me please.
I managed to pass through the error with the following fix:
public ATM(){
for(int i = 0; i<10 ; i++){
acct[i] = new Account();
acct[i].set_account_id(i+1);
acct[i].set_account_balance(100);
}
//you must set their id's to values as specified in the assignment
}
However I am not sure if this is correct or not. Is it?
The problem here is that this line:
private Account[] acct = new Account [10];
only initializes space for 10 Account instances, it doesn't actually construct 10 account instances and put them in the array.
In the for loop in your ATM constructor, you need to first call acct[i] = new Account();
Beside creating array you also need to fill it with objects. Update your code in ATM constructor:
for (int i = 0; i < 10; i++) {
acct[i] = new Account(); // add this line to crate account
// and place it in array
acct[i].set_account_id(i + 1); // also you are getting error here
acct[i].set_account_balance(100); // not here because you ware trying to
// invoke method on `null`
}