I'm hoping someone can help me out with a question that I've been stuck on for quite a while.
Just to clarify the scenario. There is a show being held in a theatre that can hold 180 people. They allow online bookings that are written to a text file "bookings.txt" Individual bookings are single that only have a seat, contact and payment status record. Whereas group bookings have seats, a contact number, payment status, group name and group size records.
So far I have created the Bookings and GroupBookings classes. I'll show them below:
/**
*
* #author OP
*/
public class Booking
{
public String seat;
public String contact;
public double cost;
public boolean paid;
//Constructor
public Booking(String st, String ct, int cost, boolean pd)
{
seat = st;
contact = ct;
this.cost = cost;
paid = pd;
}//end of Booking
//Getters
public String getSeat()
{
return seat;
}//end of getSeat
public String getContact()
{
return contact;
}//end of getContact
public boolean isPaid()
{
return paid;
}//end of isPaid
public double getCost()
{
//Determining what discount should be applied to their seat location
if (seat.contains("A") || seat.contains("B") ||
seat.contains("C") || seat.contains("D"))
{
cost = 200;
}
else
{
if (seat.contains("E") || seat.contains("F") ||
seat.contains("G") || seat.contains("H"))
{
cost = 160;
}
else
{
if (seat.contains("I") || seat.contains("J") ||
seat.contains("K") || seat.contains("L"))
{
cost = 120;
}
}
}//end of nested if statement
return cost;
}//end of getCost
#Override
public String toString()
{
return seat + "\t" + "R" + cost + "\t" + paid;
}//end of toString
}//end of class booking
/**
*
* #author OP
*/
public class GroupBooking extends Booking
{
private String groupName;
private int groupSize;
public GroupBooking(String st, String ct, boolean pd, String gn, int gs)
{
//Variables from previous class (using inheritance)
super.seat = st;
super.contact = ct;
super.paid = pd;
//New variables for this class
groupName = gn;
groupSize = gs;
}//end of GroupBooking
#Override
public double getCost()
{
cost = super.getCost();
for (int i = 0; groupSize % 4 > i; i++)
{
cost = cost - 60;
i++;
}//end of for loop
return cost;
}//end of getCost
public int getGroupSize()
{
return groupSize;
}//end of getGroupSize
public String getGroupName()
{
return groupName;
}//end of getGroupName
#Override
public String toString()
{
return seat + "\t" + "R" + cost + "\t" + groupName;
}//end of toString
}//end of class GroupBooking
Now for the question that I am stuck on:
A new class has to be created called BookingManager. From there I have to declare two instance variables in the class of one-dimensional array that can be used to store up to 180 Booking or GroupBooking objects. An integer counter must also be created to keep track of how many Bookings are stored in the array. (These two instance variables should not be accessible from outside the class)
I'm still a newbie in coding and I'm unsure of what to do here. The follow-up question is also giving me difficulties:
A contractor then has to be created to read the information from the text file "bookings.txt". Each line either contains a single Booking or a GroupBooking object. Read each line from the file and instantiate the appropriate type of object (Booking or GroupBooking) and add it to the array. (Note in the case of GroupBooking you must create an object in the array for each member of the group. Exp for a group of six you have to have six separate GroupBooking objects in the array.)
I know a file scanner is needed from the second question but I have no idea whether to use a for loop or an if statement to differentiate between a single booking or a group booking.
If anyone can help I would truly appreciate it. This topic is still very new to me.
To prevent a variable being accessible outside a class declare the variable "private". e.g.
private String costtotal="";
An instance variable "is not" static ("is not" a class member variable), and are a global variable only declared at the top of the class code below the import statements, so exist until the class exits.
In your manager class you need a global variable array Booking class
Booking[] bookings;
private String costtotal=""; // e.g.
// in the constructor read the bookings file and find the number of bookings made
//int totalbooked=...whatever reading the file data counts to of bookings made;
bookings=new Booking[totalbooked];
// create and fill each Booking object and assign it to its index on the array in a loop
bookings[loopcount]=new Booking(st,ct,cost,pd);
Different schemes of class systematics of coding
// bean syntax in a java bean framework class type
public void setCosttotal(String costtotal){
this.costtotal=costtotal;
}
//bean syntax
public String getCosttotal(){
return costtotal;
}
// normal non bean syntax 1
public String costTotal(String csttot){
return (String)csttot;
}
// somewhere else in code in scope to global variable
costtotal=costTotal(valuein);
// normal non bean syntax 2
public String costTotal(String csttot){
costtotal=csttot;
return costtotal;
}
Related
Okay, so I'm working on a homework assignment where I have a staff of 10 salespeople. We have a contest for the greatest number of sales. The assignment wants the user to enter 10 integer values as a number of sales and then once they've all been entered the salesperson with the highest value will be returned.
What she wants:
A Class "Sales" with (String name and Integer sales) values.
A while loop where the user inputs integers for number of sales
What I'm attempting to do. I assume the names of the salespeople at the company are known, so I just created an array strSalesPerson of 10 fictitious names. I created a counter salespersonCounter to create the counter for the while loop for user input. I'm trying to basically create salesperson1, salesperson2, salesperson3, and so on by creating a variable with the string "salesperson" concatenated with the counter. I want to use that as the name of the instance for each salesperson entered into the Sales Class.
Sales Class
Just for reference, the class I've created and trying to create instances of is as follows:
private String salesname;
private Integer numsales;
public Sales(String name, Integer sales) {
this.salesname = name;
if (sales >= 0.0) {
this.numsales = sales;
}
}
// Setter for name
public void setName(String name) {
this.salesname = name;
}
// Getter for name
public String getName() {
return salesname;
}
// Setter for Sales
public void setSales(Integer sales) {
if (sales >=0) {
this.numsales = sales;
}
}
// Getter for Sales
public int getSales() {
return numsales;
}
} // End of Class
TestSales
This is where I will get the user input and save it as an instance of the Sales class. However, right now I'm just going to use the current instance from the array of names and the static integer 3 to ensure that I get the other pieces functioning correctly and then I'll switch over to user inputs from there.
// Import Scanner
import java.util.Scanner;
public class TestSales {
public static void main(String[] args) {
// create scanner to obtain input from command window
Scanner input = new Scanner(System.in);
// Initialize variables
int salespersonCounter = 1;
// Fill Salesperson names
String[] strSalesPerson = new String[]{"Mark Hasselback","Gary Moore","Shelly Hemingway", "Susan Meagre","Nick Pantillo","Craig Grey","Alice Reese","Mickey Greene","Chaz Ramirez","Kelly Southerland"};
while (salespersonCounter <=10) {
String salespersoninstance = ("salesperson"+ salespersonCounter);
String currsalesperson = strSalesPerson[salespersonCounter -1];
System.out.printf("%s");
Sales salespersoninstance = new Sales(strSalesPerson[salespersonCounter -1],);
System.out.printf("%s is %s!%n",salespersoninstance,currsalesperson);
salespersonCounter += 1;
}
}
}
The problem I am running into is here:
Sales salespersoninstance = new Sales(strSalesPerson[salespersonCounter -1],3);
instead of accepting the string value of salespersoninstance (in this case salesperson1) as the name of the instance of the Sales Class, it is telling me that salespersoninstance is a duplicate local variable. It is interpreting it I guess as me trying to define a new variable with the same name as one I've already declared?
Basically what I want is with the while counter, create a string variable salesperson1, salesperson2, salesperson3 and so on with "salesperson" + salespersonCounter, and use that resulting string to name the instance of the Sales class. That way I can then say Sales salespersoninstance = new Sales(strSalesperson[salespersoncCounter -1], userinput)
To help you a bit forward:
String[] salePersonNames = new String[]{"Mark Hasselback", "Gary Moore", "Shelly Hemingway", "Susan Meagre", "Nick Pantillo", "Craig Grey", "Alice Reese", "Mickey Greene", "Chaz Ramirez", "Kelly Southerland"};
for (int i = 0; i < salePersonNames.length; i++) {
Sales salesPerson = new Sales(salePersonNames[i], 3);
System.out.printf("%s is %s!%n", salesPerson.getName(), salesPerson.getSales());
}
I'm not sure why, but I'm having a problem launching the code that I put together. For some reason, the code shows fatal errors when I enter a parameter within the methods. I have checked it several times but could not figure out what I did wrong.
Any advice would be appreciated.
public class songcode
{
/**
* #param args the command line arguments
*/
public class Songwriter{
private int song;
//variable for the amount of songs played
private int royalty;
//variable for the amount of payments
private int identification_number;
//id number of the song writer
public String first_name;
//string for the first name of songwriter
public String last_name;
//string for the last name of the songwriter
public int Adding_song(){
song = song + 1;
if(song > 100){
System.out.println("You are a big star!");
}
return(song);
}
public int Requesting_check(){
royalty = royalty + 10;
System.out.println("You just got payed");
return royalty;
}
public static void main(String[] args){
}
}
}
See the comments for some quick help :)
public class SongWriter {
private int song;
//variable for the number of songs played
private int royalty;
//variable for the number of payments
private int identification_number;
//id number of the song writer
public String first_name;
//string for the first name of songwriter
public String last_name;
//string for the last name of the songwriter
public SongWriter(int myFavSong){
//define default values for vars above
this.song = myFavSong;
//'This' references the Songwriter object not required but useful practice.
}
// Lower case first word upcase second : camelCase
public int addingSong(int numSongs){
song = song + numSongs;
if(song > 100){
System.out.println("You are a big star!");
}
return(song);
}
public int requestingCheck(){
royalty = royalty + 10;
System.out.println("You just got payed");
return royalty;
}
// The main method shouldn't be nested another class
public static void main(String[] args){
//In java because our variables and functions are not static
//you need a reference to your SongWrite object
SongWriter songWriter = new SongWriter();
// Notice I modified your function to take in an int as a param
songWriter.song = addingSong(5);
System.out.println(songWriter.song);
}
}
because of lack information it is a little hard for us to solve your problem. Please provide us exacly what steps did you take and what errors did you get.
From what i see now, since your are using inner class (class inside of another class), you should make it static:
static class Songwriter{/*your code here*/ }
When you got that you can create an object of that class in your main() by calling your outer class, so in your case it would be:
songcode.Songwriter name = new songcode.Songwriter();
Now you can use your methods that are within your inner class by using name.method() like:
name.Requesting_check();
for(int i = 0; i<200; i++){
name.Adding_song();
}
Personally i would create a new java file called Songwriter.java, add a constructor and work with that, but maybe that's not what you were testing here ;-)
Hope it did help you and please next time provide more detailed informations, so we can give you an exact answer without guessing what's wrong and what exacly do you want to achieve with your code.
These are the instructions for this assignment. Any help would be appreciated. I am a rookie when it comes to java and cant seem to figure this out.
This exercise has two classes. The first class is named ObjectsToArrayList. The second class is called just Objects.
Your responsibility is to create the Object class and figure out how the ObjectsToArrayList class works.
The ObjectsToArraylist class will create an ArrayList of objects. It will ask for and populate the data fields of an Object, then add it to the ArrayList. This can be done for as many instances of the Object that the user wants to enter.
Requirements for the Object Class.
2 data fields: int obj_id, String obj_name.
2 Constructors: No-Arg and one that takes both values and assigns them to the data field.
Gets and sets for both data fields
A toString() method that returns output like:
The object ID is 22 and the name is Andrea
Here's my code
import java.util.*;
/**
*
* #author Student
*/
public class ObjectsToArrayList {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
ArrayList <Object> objectList = new ArrayList();
System.out.println("Please enter information for your favorite object!");
do { // collect an indicator to determine the method to call
Object object = new Object();
System.out.println("Enter a whole number for the ID of your object:\n"
+ "or enter 99 to quit.");
int tmpInt = input.nextInt();
// if 99 is entered exit the loop.
if (tmpInt == 99) {
break;
}
object.setObj_id(tmpInt);
input.nextLine();
// ask for the Object Name
System.out.println("Please enter the name of the Object:");
object.setObj_name(input.nextLine());
objectList.add(object);
} while (true); // this is a contineous loop if the break isn't included.
for(Object object:objectList) {
System.out.println(object.toString());
}
}
}
//****************************************************
//**** Objects Class is below this block **
//****************************************************
class Object {
// enter object code here (This is the part I cannot figure out)
}
Here are examples of constructors:
class Objects{
// This is a constructor with no argument
public Objects(){
}
// This is a constructor with 2 arguments
public Objects(int obj_id, String obj_name){
}
}
You can refer in the link below to learn more about creating constructors and assigning values to fields:
http://docs.oracle.com/javase/tutorial/java/javaOO/constructors.html
Note: Do not use Object as a class because Object is the root of the class hierarchy. Every class has Object as a superclass. All objects, including arrays, implement the methods of this class.
http://docs.oracle.com/javase/8/docs/api/java/lang/Object.html
Try something like this:
public class ObjectsToArrayList {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
ArrayList <Object> objectList = new ArrayList();
System.out.println("Please enter information for your favorite object!");
do { // collect an indicator to determine the method to call
Object object = new Object();
System.out.println("Enter a whole number for the ID of your object:\n"
+ "or enter 99 to quit.");
int tmpInt = input.nextInt();
// if 99 is entered exit the loop.
if (tmpInt == 99) {
break;
}
object.setObj_id(tmpInt);//runs the setObj_id method in the Objects class
//for the users input
input.nextLine();
// ask for the Object Name
System.out.println("Please enter the name of the Object:");
object.setObj_name(input.nextLine());//runs the setObj_name method in the Objects class
//for the users input
objectList.add(object);
} while (true); // this is a contineous loop if the break isn't included.
for(Object object:objectList) {
System.out.println(object.toString());//prints out what the toString method returns in
//the Objects class
}
}
}
//****************************************************
//**** Objects Class is below this block **
//****************************************************
public class Objects
{
//add stuff like methods and instance variables
private int ID;
private String name;
public Objects(){//default constructor
}
public Objects(int i, String n){//constructor to change both ID and name at the same time
ID = i;
name = n;
}
public void setObj_id(int i){//constructor to change only ID
ID = i;
}
public void setObj_name(String n){//constructor to change only name
name = n;
}
public String toString(){
return (name + ": " + ID);
}
}
Ok so you want to create your own object soo have 2 classes rather, personProfile and arrayOfProfiles
So class personDetails object note seperate class file not *not in same file
class personProfile{
private int ID = 0;
private String Name = "";
public personProfile(int id,String name){
ID = id;
Name = name;
}
public int getID(){
return ID;
}
public String getName(){
return name;
}
}
now the other class* different file
class arrayOfProfiles{
personProfile profiles[] = new personProfile[0];
public personProfile[] array(){
return profiles;
}
public void addProfileToArray(personProfile profileObject){
personProfile arrayMod = new personProfile[profiles.length+1];
for(int i = 0;i<profiles.length;i++){
arrayMod[i] = profiles[i];
}
arrayMod[arrayMod.length-1] = profileObject;
}
public static void main(String args[]){
arrayOfProfiles profiles = new arrayOfProfiles();
for(int i = 0;i<5;i++){
int id = Integer.parseInt(JOptionPane.showInputDialog("enter ID ");
String name = JOptionPane.showInputDialog("enter name");
profiles.addProfileToArray(new personProfile(id,name));
}
for(int i =0;i<profiles.array().length;i++){
System.out.println("ID :"+profiles[i].getID()+" name - "+profiles[i].getName());
}
}
}
The private createAccountID() method should create a new unique id everytime an Account is created i.e. the first account created will have the ID
“A1000”. The account ID will increase by 1 for each new account, i.e. the second
will have ID “A1001” etc. and there shouldnt be any duplicates.
I am not really sure how to start this method, except that i created a static variable called counter that is set to 0. I think i have to use a .equals() method or something to make sure that the first isn't equal to the new one else it will print an error messege like ("Duplicate")
I am also not sure whether to go with public void createAccountID() or
public String createAccountID()
Here is the code:
public class Account
{
private Customer customer;
private String accountID;
private double balance;
private static int counter = 0;
private static final double OPENING_BALANCE = 0.0;
public Account()
{
setCustomer(new Customer());
setBalance(OPENING_BALANCE);
createAccountID();
}
public Account(Customer theCustomer, double theBalance)
{
setCustomer(theCustomer);
setBalance(theBalance);
createAccountID();
}
private void createAccountID()<------------------------------------------------
{
accountID = "A";
for(counter = 0; counter >= 0; ++counter){
accountID+=counter;//stuck in loop doesnt work.
//just thought id try it
}
}
public void setCustomer(Customer theCustomer)
{
if(theCustomer == null){
customer = new Customer();
}
else{
customer = theCustomer;
}
}
public Customer getCustomer()
{
return customer;
}
public void setBalance(double theBalance)
{
if(theBalance <= OPENING_BALANCE){
System.out.println("Error. No Negative values");
}
else{
balance = theBalance;
}
}
public double getBalance()
{
return balance;
}
}
Any help appreciated Cheers
You can set your 'counter' starting value to 1000 and concatenate it to 'A' char to set in 'accountID'.
To make sure, that there is no duplicates, you can use a Set interface. For example, a HashSet implementation in a private static field.
Another variant is to use a TreeSet and use its last() method to obtain the latest ID. Then you can avoid using a counter. For instance, you can store a starting counter with value '1000' and increment it with treeSet.last() and then store the result.
Also, I`m not sure why do you need a public createAccountID(). This is something, that should be incapsulated inside your class and should not be invoked externally.
Maybe it makes sense to change your accountID field to int and concatenate to 'A' in a getter method.
//
Or maybe you just need a static counter with a starting value '1000' and then call in constructor:
this.accountID = 'A' + counter++;
If there aren't multiple threads involved, using the static counter will ensure that there aren't duplicates.
In case of multiple threads, you could use an AtomicInteger. In this case, make sure that first you increment the AtomicInteger with incrementAndGet(1) and after you create the ID:
private static final AtomicInteger counter = new AtomicInteger(1000);
private static final String PREFIX = "A";
private String accountID;
private void createID() {
final int number = counter.incrementAndGet(1);
accountID = PREFIX + number;
}
Note that the createID method should be private, as stated by #Michael Cheremukhin.
Create a static variable counter, concatenate it to A and increment it. Keep your function private, you shouldn't call it from outside your class.
private void createAccountID()
{
accountID = "A" + counter++;
}
I am done with this assignment think god, and was wondering if someone could please check it so I can make sure there are no errors, it seems like I work hard on these programs but always doing something wrong. I am doing this course online so I have a hard time communicating with the instructor. I think my equals to methods might be wrong but, they seem to have no error when running the program and the program is 100% done. Please take the time to look over it, and thank you so much for your time.
Assignment:
About the first class
Create a class named RoomDimension that has two fields: one for the length of the room and another for the width. The RoomDimension class should have two constructors: one with no parameters (a default) and one with two parameters. The class should have all of the appropriate get and set methods, a method that returns the area of the room, a toString method that will allow us to print the length, width and area of the room and an equals method to compare room dimensions.
About the second class
Create another class named RoomCarpet that has two fields: one is a RoomDimension object and the other is a field that holds the cost of carpet per square foot. The class should have two constructors: one with no parameters and one with the two field parameters (RoomDimension and double). The class should have a get and set method for each field, a method that returns the total cost of carpeting the room, a toString method that will print all of the room information (length, width, area) and cost of the carpet per square foot and the total cost to carpet the room. (Dollar amounts should be displayed with two decimal places.), and an equals method that compares room dimensions and carpet cost.
About the application program
Write an application program that contains one RoomDimension object and one RoomCarpet object. The program should allow the user to enter the length and width of the room and the cost of the carpet per square foot. The program should instantiate both objects and use a simple System.out.println statement to print all of the information about the RoomCarpet object.
MY code:
import java.text.DecimalFormat;
public class RoomCarpet {
private RoomDimension rmSize;
private double pricePerSqFt;
//default constructor
public RoomCarpet()
{
this.rmSize = new RoomDimension();
this.pricePerSqFt = 0.00;
}
//parameters constructor
public RoomCarpet(RoomDimension rmSize, double pricePerSqFt)
{
this.rmSize = new RoomDimension(rmSize.getRmLength(),rmSize.getRmWidth());
this.pricePerSqFt = pricePerSqFt;
}
//accessor methods
public RoomDimension getRmSize()
{
return new RoomDimension(rmSize.getRmLength(),rmSize.getRmWidth());
}
public double getPricePerSqFt()
{
return this.pricePerSqFt;
}
// mutator methods
public void setRmSize(RoomDimension rmSize)
{
this.rmSize = new RoomDimension(rmSize.getRmLength(), rmSize.getRmWidth());
}
public void setPricePerSqFt(double pricePerSqFt)
{
this.pricePerSqFt = pricePerSqFt;
}
// Or price for the room to be carpeted
public double rmTotalCost()
{
return rmSize.getAreaRoom() * pricePerSqFt;
}
//toString method
public String toString()
{
DecimalFormat dollar = new DecimalFormat("$#,##0.00");
String str = this.rmSize.toString() + " Price per sq. ft : " +dollar.format(pricePerSqFt) + " Price to carpet Room: " + dollar.format(rmTotalCost()) + '\n';
return str;
}
public boolean equals(RoomCarpet object2)
{
boolean status;
if ((this.equals(object2)==true)&&(this.pricePerSqFt==object2.pricePerSqFt))
status = true;
else
status = false;
return status;
}
}
public class RoomDimension {
private int rmLength;
private int rmWidth;
//Default constructor
public RoomDimension()
{
rmLength=0;
rmLength=0;
}
// constructor with parameters
public RoomDimension(int rmLength, int rmWidth)
{
this.rmLength=rmLength;
this.rmWidth=rmWidth;
}
// accessor methods
public int getRmLength()
{
return this.rmLength;
}
public int getRmWidth()
{
return this.rmWidth;
}
//mutator methods
public void setRmLength(int rmLength)
{
this.rmLength=rmLength;
}
public void setRmWidth(int rmWidth)
{
this.rmWidth =rmWidth;
}
//area of the room
public int getAreaRoom()
{
return this.rmLength * this.rmWidth;
}
//toString Method
public String toString()
{
String str = "Room Length: " + this.rmLength + " Room Width: " + this.rmWidth + " Area of Room: " + this.getAreaRoom();
return str;
}
public boolean equals(RoomDimension object2)
{
boolean status;
if (this.getAreaRoom() == object2.getAreaRoom())
status = true;
else
status = false;
return status;
}
}
import java.util.Scanner;
public class CarpetPrice {
public static void main(String[] args)
{
RoomDimension rmSize;
RoomCarpet rmCarpet;
Scanner keyboard = new Scanner(System.in);
rmSize=new RoomDimension();
System.out.println(" Please enter the length of the room: ");
int rmLength= keyboard.nextInt();
rmSize.setRmLength(rmLength);
System.out.println("Please enter the rooms width: ");
int rmWidth = keyboard.nextInt();
rmSize.setRmWidth(rmWidth);
System.out.println("Please enter the price per sq foot: ");
double pricePerSqFt = keyboard.nextDouble();
rmCarpet = new RoomCarpet(rmSize, pricePerSqFt);
System.out.println("\n"+rmCarpet.toString());
}
}
The equals method must have an Object argument and you have to override the hashCode method too.
#Override
public boolean equals(Object obj)
{
}
I would say that for RoomDimension, two objects are equal only if both length and width match. Especially if you're laying carpet, a 4x5 room would be much different from a 1x20 hallway, even though the total area is the same. For the RoomCarpet object, again equal only if both the dimensions are equal and the price is the same, I guess.
Also, I would write some tests because you may be surprised at what happens when you call RoomCarpet's .equals() method (as written above).
Finally, pay attention to your indenting because that's important for any reader of your code.