How to add Multiple objects using indexes in a ArrayList - java

I'm doing a menu-based system where it will calculate my monthly rent using specific variables (double - monthlyRent, double waterBill, double energyBill etc.)
The program starts with prompting the user to select an option:
(1) create a budget invoice (this is where a projected monthly rent invoice will be calculated)
When the user selects this option I want to use an ArrayList to store the monthly rent invoices. I have a variable where the user can put an InvoiceID to search an already existing monthly rent invoices or delete etc.
My problem is how to use specific indexes in my ArrayList to input monthly rent, water bill and so forth and the next index will be a different monthly rent, waterbill, energy bill etc.). In a general sense, store multiple variable and variable types within 1 index of the ArrayList.
My ArrayList is in its own class, different from the function that I want to create to generate monthly budget invoices. My problem is how to prompt user input for each rent variable and store all of those inputs in its proper index of the ArrayList where that specific monthly invoice will be stored. The variables are double, string and int types.
import java.util.ArrayList;
public class InvoicerHub {
static ArrayList<Object> invoicerSys = new ArrayList<Object>();
}
import java.util.ArrayList;
import java.util.Scanner;
public class BudgetInvoice extends InvoicerHub {
protected double monthlyRent ;
protected double waterBill;
protected double energyBill;
protected double carRent;
protected double internetRent;
protected String invoiceID;
public int counter = 0;
static Scanner myScan= new Scanner(System.in);
public double getMonthlyRent() {
return monthlyRent;
}
public void setMonthlyRent(double monthlyRent) {
this.monthlyRent = monthlyRent;
}
public double getWaterBill() {
return waterBill;
}
public void setWaterBill(double waterBill) {
this.waterBill = waterBill;
}
public double getEnergyBill() {
return energyBill;
}
public void setEnergyBill(double energyBill) {
this.energyBill = energyBill;
}
public double getCarRent() {
return carRent;
}
public void setCarRent(double carRent) {
this.carRent = carRent;
}
public double getInternetRent() {
return internetRent;
}
public void setInternetRent(double internetRent) {
this.internetRent = internetRent;
}
public String getInvoiceID() {
return invoiceID;
}
public void setInvoiceID(String invoiceID) {
this.invoiceID = invoiceID;
}
public static InvoicerHub getInvoice()
{
invoicerSys = new ArrayList<>();
if (invoicerSys.isEmpty()== true)
{
} // This is where I'm stuck.

Related

Issue with referncing objects that do not have a name

I´m new to programming and I have this task to implement a simple booking System for bus tickets.
We´re supposed to implement a method that adds new bus routes using the attributes: busNumber, start, destination, price, currency. To save the bus routes I´m using an arraylist and save new objects like this:
Booking.add(new Booking(1, "France", "Latvia", 2.05, Currency.EUR))
My issue now is working with those objects since they don´t have a name. I don't know the exact number of objects, so I have to do it this way (i think so at least). Where the issue occurred is at the method "remove", that is supposed to remove a bus route. I thought I could use an Iterator to iterate through the ArrayList and compare the busNumbers but it´s not working.
Another issue I have is, that when I want to print all the objects in my Array list it just prints the last object as many times as there are objects in my ArrayList. Also, my method and attributes are all static now otherwise I wouldn´t know how to use them in another class.
Does anybody has some advice for a newbie please?
My Code is below:
import java.util.ArrayList;
import java.util.Iterator;
public class Booking {
static int busNumber;
static int customerID = 1; //First customerID starts with 1
static String name;
static double price;
static int invoiceNumber = 1; //First invoicenumber starts with 1.
static String start;
static String destination;
static Currency currency;
static ArrayList<Booking> bookable = new ArrayList<Booking>();
//Constructor
public Booking(int busNumber, String start, String destination, double price, Currency currency) {
this.busNumber = busNumber;
this.start = start;
this.destination = destination;
this.price = price;
this.currency = currency;
}
public int getBusNumber() {
return busNumber;
}
public static void add(Booking add) { // add-method. Adds the bus routes to the booking system
bookable.add(add);
}
public static void remove(int busNumber) { // Here´s one of my issues. That´s what i have.
Iterator<Booking> it = bookable.iterator();
if ( == busNumber) {
bookable.remove(it);
}
}
public static void listRoute() {
for (Booking element : bookable) {
Terminal.printLine(toString(element));
}
}
public static String toString(Booking element) {
return "000" + busNumber + " " + start + " " + destination + " " + price + " " + currency;
}
}
My second class which is later supposed to be the UI:
public class Input {
public static void main(String[] args) {
Booking.add(new Booking(1, "Mannheim", "Karlsruhe", 2.05, Currency.EUR));
Booking.add(new Booking(2, "Heidelberg", "Karlsruhe", 3.05, Currency.JPY));
Booking.add(new Booking(3, "Germersheim", "Karlsruhe", 4.05, Currency.USD));
Booking.listRoute();
}
}
The Output is: "0003, "Germersheim", "Karlsruhe", 4.05, Currency.USD" 3 times..

Do i need to add objects dynamically in this case?

So i've been asked to create a simple solar system simulator for my coursework. Our lecturer has set out very specific guidelines in terms of the structure of constructors and methods of our classes.
I've been thinking about this for a couple of hours and don't understand how i can make this work without dynamic object allocation. I want to add planets onto the Planet[] array so they can be indexed, but i don't know how i should create the objects considering a requirement is that you can add planets to the system until the user types 'DONE'.
The Planet class is not one of the requirements but he recommended we use a class that can store the variables for a single planet and do calculations on it. Whereas the data should be stored in the main SolarSystem class. We also need to use a FantasySolarSystem class to read data from the user and deal with output.
import java.util.*;
public class SolarSystem{
public static final int PLANET_MAX = 10;
public static void main(String[] args){
String systemName;
Planet[] planetArray = new Planet[PLANET_MAX]; //const for array size seemed easier than dynamically allocating memory
SolarSystem mySystem = new SolarSystem("Boris");
// below is testing the addplanet function
addPlanet("Jimmy", 10, 100);
System.out.print(Planet[0].planetName);
}
public SolarSystem(String name){
systemName = name;
}
public static void addPlanet(String planetName, double planetMass, double planetDistance){
Planet newPlanet = new Planet(planetName, planetMass, planetDistance);
// all i want to do here is add planets on to the array
Planet[0] = newPlanet;
}
}
Just for reference here is the Planet class:
public class Planet{
private String planetName;
private double planetMass;
private double planetDistance;
private double planetPeriod;
public Planet(String planetName, double planetMass, double planetDistance){
this.planetName = planetName;
this.planetMass = planetMass;
this.planetDistance = planetDistance;
}
//sets the period for the current object
public static calculatePeriod(double planetDistance){
double period = Math.sqrt(planetDistance*planetDistance*planetDistance);
setPlanetPeriod(period);
}
//accessors
public String getPlanetName(){
return planetName;
}
public double getPlanetMass(){
return planetMass;
}
public double getPlanetDistance(){
return planetDistance;
}
public double getPlanetPeriod(){
return planetPeriod;
}
//mutators
public void setPlanetName(String planetName){
this.planetName = planetName;
}
public void setPlanetMass(double planetMass){
this.planetMass = planetMass;
}
public void setPlanetDistance(double planetDistance){
this.planetDistance = planetDistance;
}
public void setPlanetPeriod(double planetPeriod){
this.planetPeriod = planetPeriod;
}
}
Any assistance would be much appreciated.
edit: I would just write it and test it but im getting errors saying, cannot find symbol in places referring to the object array
edit2: Fixed the accessing non-static methods from static methods issue, but still having problems with adding objects to arrays (still have 3 more cannot find symbol errors, with systemName=name; and both times i use Planet[0])

Java Phone/Item Picker

I'm creating a project in which users input the basic specifications of a phone and the program will compare this data to phones on the market now and return results of phones they would likely be happiest with.
I've currently only been able to get to a point in which users input this data, and as someone who's only been programming for a month, I have no clue as to how to compare this data to previously determined data, can someone help me finish this out?
import cs1.Keyboard;
public class CoolProject {
public static void main (String [] args) {
double num_Memory, num_Screen, num_ProcessorSpeed, num_ProcessorCores, num_Battery, num_Camera, num_PPI;
System.out.println("The most noticeable part of a phone is its' screen size. \nEnter the minimum screen size you'd like your phone to have: ");
num_Screen = Keyboard.readInt();
System.out.println("Fantastic! Most phones today have a 720p, 1080p, or 2K screen. \nWhat's the minimum screen resolution you'd like to have: ");
num_PPI = Keyboard.readInt();
System.out.println"(Nice! Now you're going to want to pick a battery to help power that display! What's the smallest battery you'd like to have: ");
num_Battery = Keyboard.readInt();
System.out.println("Great! So to run that powerhouse, you'll need a beast of a processor. How many cores do you want in your CPU: ");
num_ProcessorCores = Keyboard.readInt();
System.out.println("How fast do you want it to be? Keep in mind most phones run between 1 and 2.5ghz: ");
num_ProcessorSpeed = Keyboard.readInt();
System.out.println("Perfect! Last but not least, how many megapixels do you want in your phone? Remember most phones have between 4 and 21 Megapixels: ");
num_Camera = Keyboard.readInt();
}
}
You have a group of fields that you want to consider as one object. Let's call these fields "phone specifications".
So, you create a class to store these fields and their values. Let's call the class PhoneSpecification.
package com.ggl.testing;
public class PhoneSpecification {
private double num_Memory, num_Screen, num_ProcessorSpeed,
num_ProcessorCores, num_Battery, num_Camera, num_PPI;
private String name;
private String manufacturer;
public double getNum_Memory() {
return num_Memory;
}
public void setNum_Memory(double num_Memory) {
this.num_Memory = num_Memory;
}
public double getNum_Screen() {
return num_Screen;
}
public void setNum_Screen(double num_Screen) {
this.num_Screen = num_Screen;
}
public double getNum_ProcessorSpeed() {
return num_ProcessorSpeed;
}
public void setNum_ProcessorSpeed(double num_ProcessorSpeed) {
this.num_ProcessorSpeed = num_ProcessorSpeed;
}
public double getNum_ProcessorCores() {
return num_ProcessorCores;
}
public void setNum_ProcessorCores(double num_ProcessorCores) {
this.num_ProcessorCores = num_ProcessorCores;
}
public double getNum_Battery() {
return num_Battery;
}
public void setNum_Battery(double num_Battery) {
this.num_Battery = num_Battery;
}
public double getNum_Camera() {
return num_Camera;
}
public void setNum_Camera(double num_Camera) {
this.num_Camera = num_Camera;
}
public double getNum_PPI() {
return num_PPI;
}
public void setNum_PPI(double num_PPI) {
this.num_PPI = num_PPI;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getManufacturer() {
return manufacturer;
}
public void setManufacturer(String manufacturer) {
this.manufacturer = manufacturer;
}
}
You would create an instance of this class for each phone you want to use in the comparison. You would create one instance of this class with the values received from the user.
Then, you compare the user phone specifications with the specifications you already created for the various phones.

Inherited variables are not displaying in the subclass

I'm having an issue with the inherited variables not displaying in the subclass.
Heres the code...
// Class to instantiate and call
public class UseOrder
{
public static void main(String[] args)
{
// Instantiate classes
Order objOrder=new Order();
ShippedOrder objShip=new ShippedOrder();
//Promt for data
objOrder.SetName();
objOrder.SetNum();
objOrder.SetPrice();
objOrder.SetQuantity();
// Display
objShip.Display();
}
}
//Heres the parent class
public class Order
{
//Declare variables
public String CustName;
public int CustNum,QuantityOrdered;
public double Price,TotalPrice;
//Assign Variables using set methods
public void SetName()
{
this.CustName=JOptionPane.showInputDialog("Enter customer Name");
}
public void SetNum()
{
this.CustNum=Integer.parseInt(JOptionPane.showInputDialog("Enter customer number"));
}
public void SetQuantity()
{
this.QuantityOrdered=Integer.parseInt(JOptionPane.showInputDialog("Enter quanntity ordered"));
}
public void SetPrice()
{
this.Price=Double.parseDouble(JOptionPane.showInputDialog("Enter product price"));
}
//Get methods for these variables
public String GetName()
{
return CustName;
}
public int GetNum()
{
return CustNum;
}
public int GetQuantity()
{
return QuantityOrdered;
}
public double GetPrice()
{
return Price;
}
//Method to calculate Total Price
public double ComputePrice()
{
return TotalPrice=QuantityOrdered*Price;
}
// Method to display
public void Display()
{
JOptionPane.showMessageDialog(null,CustName+" with customer number "+CustNum+" ordered "+QuantityOrdered+" products. \nThe price for one unit is " + Price+" and the total price is "+ComputePrice());
}
}
and heres the subclass
public class ShippedOrder extends Order
{
//Shipping and handling value
private double ShipFee=4.00;
// method to override ComputePrice in Order
public double ComputePrice()
{
return super.TotalPrice=(super.QuantityOrdered*super.Price)+ShipFee;
}
//Display the data
public void Display()
{
JOptionPane.showMessageDialog(null,super.GetName()+" with customer number "+super.GetNum()+" ordered "+super.GetQuantity()+" products. \nThe price for one unit is " + super.GetPrice()+" and the total price is "+ComputePrice());
}
}
You populate a different object than you're displaying, so no wonder you get no values. You should change main to
public static void main(String[] args)
{
// Instantiate classes
ShippedOrder objShip=new ShippedOrder();
//Promt for data
objShip.SetName();
objShip.SetNum();
objShip.SetPrice();
objShip.SetQuantity();
// Display
objShip.Display();
}
because every ShippedOrder is also an Order.
public static void main(String[] args)
{
// Instantiate classes
Order objOrder=new Order();
ShippedOrder objShip=new ShippedOrder();
//Promt for data
objOrder.SetName();
objOrder.SetNum();
objOrder.SetPrice();
objOrder.SetQuantity();
// Display
objShip.Display();
}
You never set anything in objShip (the derived class). All your pre-display() method invocations were on objOrder, a different object.
Maybe you meant:
public static void main(String[] args)
{
// Instantiate classes
Order objOrder=new ShippedOrder();
//Promt for data
objOrder.SetName();
objOrder.SetNum();
objOrder.SetPrice();
objOrder.SetQuantity();
// Display
objOrder.Display();
}
objShip and objOrder are separate from one another. When you change order, it will not change ship as they are different objects. You need to call the methods on objShip in this case if you want to display it from that.
ShippedOrder objShip = new ShippedOrder();
objShip.SetName();
objShip.SetNum();
objShip.SetPrice();
objShip.SetQuantity();
objShip.Display();
and remove objOrder completely.

Account Interest Calculator: How to Pass Array Value to an Object?

I've reached a brick wall in a Java sample project been working on. My goal with this project is to calculate interest using user input to determine what kind of account is being used, and calculating based on each specific account type.
Right now I have created a factory method "public Account createAccount". I need it to accept the string parameter from the user prompt. To tell me if it is Checking, Savings or CD. Now here is where I run into trouble. I have to pass the user value for the "accttype" to a new object specific for each account type. My problem is I just don't know how to do this. Do I have to implement in the factory method? How can I pass these values? Thanks in advance
Account.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Account implements ActionListener {
JButton calculate;
private int period;
private int balance;
private int fbalance;
private int rate;
private int monthlyFee;
private String printstring;
#Override
public String toString() {
return String.format("Period: " + period + ", Balance: " + balance);
}
public int getPeriod() {
return period;
}
public void setPeriod(int period) {
this.period = period;
}
public int getBalance() {
return balance;
}
public void setBalance(int balance) {
this.balance = balance;
}
public int getRate() {
return rate;
}
public void setRate(int rate) {
this.rate = rate;
}
public int getFbalance() {
return fbalance;
}
public void setFbalance(int fbalance) {
this.fbalance = fbalance;
}
public String getPrintstring() {
return printstring;
}
public void setPrintString(String printstring) {
this.printstring = printstring;
}
public void calculate() {
for ( int i = 0; i<period; i++)
{
fbalance = balance + balance * rate - monthlyFee;
}
}
public void actionPerformed(ActionEvent e) {
calculate();
}
}
Banker.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Banker {
// Array for type of bank account
private static void createAndShowGUI() {
// Declare strings for period, balance, rate
String period;
String balance;
String rate;
// Prompt for account type
String[] accttype = { "Checking", "Savings", "CD" }; // Array of bank acct types
String input = (String) JOptionPane.showInputDialog(null, "Choose account...",
"Choose bank account type", JOptionPane.QUESTION_MESSAGE, null,
accttype, // Array of acct types
accttype[0]); // First choice
// Prompt user for input
period = JOptionPane.showInputDialog(null, "Number of periods (length):");
balance = JOptionPane.showInputDialog(null, "Beginning balance:");
rate = JOptionPane.showInputDialog(null, "Interest rate (use decimal, example: .05 = 5%):");
// Make Calculate button
JButton calculate = new JButton("Calculate");
// Make 2 Labels
JLabel blabel = new JLabel("Period: " + period);
JLabel plabel = new JLabel("Balance: " + balance);
// Setup window with flow layout and exit on close
JFrame frame = new JFrame("Interest Savings Calculator Plus");
frame.setLayout(new FlowLayout());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Add combo box, calc button and labels
frame.add(calculate);
frame.add(plabel);
frame.add(blabel);
frame.pack();
frame.setVisible(true);
//Display the window.
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
createAndShowGUI();
}
public Account createAccount(String type){
}
}
If you want to use the Account class for all three account types, I suggest adding a constructor to your Account class and a variable to hold the account type like so:
public class Account implements ActionListener {
...
private String accountType = null;
public Account(String accountType) {
this.accountType = accountType;
}
...
}
Then, you can create a new Account object in the createAccount() method and return it like so:
public Account createAccount(String type) {
Account account = new Account(type);
return account;
}
Then you can simply pass the account type in (which is what your "input" variable gets set to in the createAndShowGUI() method):
Account account = createAccount(input);
Otherwise, you could also simply add the accountType variable with getters and setters, and simply create a new Account and call a set method, but I recommend using a constructor that accepts those values as parameters.
Being that you probably also want the other variables to be set in your Account object, you could call the setters on the Account object you return, or you could modify your createAccount() method and the Account constructor to accept more parameters and pass them in when you create the new Account object.

Categories