Constructor error with encapsulation - java

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);

Related

object of class inherited from abstract class return null values from getters [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 2 years ago.
Improve this question
I have a abstract class name, abstract class mammal which is descendant of animal class, and class Lion, which is descendant of mammal. Then I have class ZooManager, I can add animals, edit animals, show all animals etc through simple console app. I have all instances saved in ArrayList.My problem is when I try to get attributes of Lion for example, I always get null. I was trying to make getters abstract in animals and then use them in Lion, but didnt work. I can remove the instance by index from ArrayList, but cant use any getter. What should I do? Thank you.
Animal class
abstract public class Animal {
protected String name;
protected int birth;
protected float amount;
protected String food;
public Animal(String name, int birth, float amount, String food) {
this.name = name;
this.birth = birth;
this.amount = amount;
this.food = food;
}
public Animal() {
}
public abstract String howToFeed();
public abstract String howToCare();
public String getName() {
return this.name; };
public int getBirth() {
return this.birth;
}
public float getAmount() {
return this.amount;
}
public String getFood() {
return this.food;
}
}
Lion class
public class Lion extends Mammal {
public Lion(String name, int birth, float amount, String food) {
super(name, birth, amount, food);
}
public Lion() {
super();
}
public String howToFeed() {
return "Lion " + name + " needs " + amount + " kg of " + food + " per day";
}
public String howToCare() {
return "Lion is an animal";
}
#Override
public String toString() {
return "Lion{" +
"name='" + name + '\'' +
", birth=" + birth +
", amount=" + amount +
", food='" + food + '\'' +
'}';
}
}
And this is ZooManager class. The part I am talking about is in the removeAnimal method and listOfAnimals method
import java.util.Scanner;
import java.util.ArrayList;
public class ZooManager {
public ArrayList<Animal> animals;
public ZooManager() {
this.animals = new ArrayList<Animal>();
}
Scanner sc = new Scanner(System.in);
private static void mainMenu() {
System.out.println("------------------ ZOO ------------------");
System.out.println("1) Add an new animal");
System.out.println("2) Remove an existing animal");
System.out.println("3) Show all animals");
System.out.println("4) Edit animal");
System.out.println("5) Show animal functions ");
System.out.println("6) End manager");
System.out.println("------------------ ZOO ------------------");
}
private static void groupMenu(){
System.out.println("1) Mammal");
System.out.println("1) Fish");
System.out.println("1) Bird");
}
private static void animalMenu(int group){
if (group == 1) {
System.out.println("1) Lion");
System.out.println("2) Bear");
} else if (group == 2){
System.out.println("1) Salmon");
System.out.println("2) Goldfish");
} else {
System.out.println("1) Eagle");
System.out.println("2) Owl");
}
}
private void addAnimal() {
Animal[][] className = {{new Lion()}, {new Eagle()}};
groupMenu();
System.out.println("Choose a group: ");
int group = sc.nextInt();
animalMenu(group);
int animal = sc.nextInt();
System.out.println("Name: ");
sc.nextLine();
String nameX = sc.nextLine();
System.out.println("Year of birth: ");
int birthX = sc.nextInt();
System.out.println("Amount of food per day: ");
float amountX = sc.nextFloat();
System.out.println("Type of food: ");
sc.nextLine();
String foodX = sc.nextLine();
animals.add(className[group - 1][animal - 1]);
System.out.println(nameX);
manager();
}
private void removeAnimal() {
System.out.println("Type index of animal you want to remove");
int index = sc.nextInt();
String nameX = animals.get(index).getName();
animals.remove(index);
manager();
}
public void manager(){
mainMenu();
int input = sc.nextInt();
if (input == 1) {
addAnimal();
} else if (input == 2){
removeAnimal();
} else if (input == 3) {
listOfAnimals();
} else if (input == 4) {
editAnimal();
} else {
System.out.println("Ending manager");
}
}
private void listOfAnimals(){
System.out.println(" index |name |birth |amount |food");
for (Animal item: animals) {
System.out.println(animals.indexOf(item) + " |" + item.getName() + " |" + item.getBirth() + " |" + item.getBirth() + " |" + item.getFood());
}
manager();
}
private void editAnimal(){
System.out.println("Index of animal u want to edit: ");
int index = sc.nextInt();
sc.nextLine();
System.out.println("1) Name");
System.out.println("2) Birth");
System.out.println("3) Amount");
System.out.println("4) Food");
System.out.println("Type number: ");
int input = sc.nextInt();
sc.nextLine();
switch (input) {
case 1 -> {
System.out.println("Type new name: ");
animals.get(index).name = sc.nextLine();
}
case 2 -> {
System.out.println("Type new year of birth: ");
animals.get(index).birth = sc.nextInt();
}
case 3 -> {
System.out.println("Type new amount: ");
animals.get(index).amount = sc.nextFloat();
}
case 4 -> {
System.out.println("Type new food: ");
animals.get(index).food = sc.nextLine();
}
}
System.out.println("done");
manager();
}
}
Update: Here is Mammal class, but for now its just copy of animal
abstract public class Mammal extends Animal{
public Mammal(String name, int birth, float amount, String food) {
super(name, birth, amount, food);
}
public Mammal() {
}
}
*Edit
The problem is here
private void addAnimal() {
Animal[][] className = {{new Lion()}, {new Eagle()}};
You create those animals without any value in their member fields. Therefore later when you read the field value is null.
Your method could be
private void addAnimal() {
groupMenu();
System.out.println("Choose a group: ");
int group = sc.nextInt();
animalMenu(group);
int animal = sc.nextInt();
System.out.println("Name: ");
sc.nextLine();
String nameX = sc.nextLine();
System.out.println("Year of birth: ");
int birthX = sc.nextInt();
System.out.println("Amount of food per day: ");
float amountX = sc.nextFloat();
System.out.println("Type of food: ");
sc.nextLine();
String foodX = sc.nextLine();
Animal[][] className = {{new Lion(namex, birthx, amountx, foodx)},
{new Eagle(namex, birthx, amountx, foodx)}};
animals.add(className[group - 1][animal - 1]);
System.out.println(nameX);
manager();
}

How to initialize object variable in another object constructor (more details)?

I'm still a beginner so cut me some slack.
I have 5 class but only 2 are needed for my question. This is a question in my assignment so no need to be too particular. I have been tasked to make a java terminal system to store and display lecturer (part time and full time), lecturers address, and classes information.
My code will check if there is a part time lecturer to display (this includes the address object since it is part of the lecturer information) . If not, it will prompt the user to enter the part time lecturer details. When entering the part time details I am not sure on how to enter the address without recreating the object.
here is my codes
This is part time class
public class PartTime extends Lecturer{
private double hourlyRate;
private int hoursWorked;
//classR = class resposible
private ClassInfo classR;
PartTime(){
classR = new ClassInfo();
}
PartTime(String staffNo, String name, int contactNo, int noClasses, Address add, double hourlyRate, int hoursWorked, ClassInfo classR){
super(staffNo, name, contactNo, noClasses, add);
this.hourlyRate = hourlyRate;
this.hoursWorked = hoursWorked;
this.classR = classR;
}
public double getHourlyRate(){
return this.hourlyRate;
}
public int getHoursWorked(){
return this.hoursWorked;
}
public void setHourlyRate(double newHourlyRate){
this.hourlyRate = newHourlyRate;
}
public void setHoursWorked(int newHoursWorked){
this.hoursWorked = newHoursWorked;
}
public void displayClassR(){
System.out.println("Class No : "+ classR.getClassNo());
System.out.println("Subject Name : "+ classR.getSubjectName());
System.out.println("Number Of Students : "+ classR.getNoStudents());
System.out.println("Start Date : "+ classR.getStartDate());
System.out.println("End Date : "+ classR.getEndDate());
}
}
This is lecturer class
public class Lecturer{
private String staffNo, name;
private int contactNo, noClasses;
private final Address add;
Lecturer(){
add = new Address();
}
Lecturer(String staffNo, String name, int contactNo, int noClasses, Address add){
this.staffNo = staffNo;
this.name = name;
this.contactNo = contactNo;
this.noClasses = noClasses;
this.add = add;
}
public String getStaffNo(){
return this.staffNo;
}
public String getName(){
return this.name;
}
public int getContactNo(){
return this.contactNo;
}
public int getNoClasses(){
return this.noClasses;
}
public void displayAdd(){
System.out.println("Unit Number : "+ add.getUnitNo());
System.out.println("Street Name : "+ add.getStreetName());
System.out.println("City : "+ add.getCity());
System.out.println("Postcode : "+ add.getPostcode());
}
public void setStaffNo(String newStaffNo){
this.staffNo = newStaffNo;
}
public void setName(String newName){
this.name = newName;
}
public void setContactNo(int newContactNo){
this.contactNo = newContactNo;
}
public void setNoClasses(int newNoClasses){
this.noClasses = newNoClasses;
}
public void setAdd(String newUnitNo, String newStreetName, String newCity, int newPostcode){
add.setUnitNo(newUnitNo);
add.setStreetName(newStreetName);
add.setCity(newCity);
add.setPostcode(newPostcode);
}
}
You can ignore the menu part
import java.io.*;
class Main{
static Scanner scan = new Scanner(System.in);
static Address add = new Address();
static ClassInfo classI = new ClassInfo();
static FullTime ft = new FullTime();
static PartTime pt = new PartTime();
static String staffNo, name, classNo, subjectName, startDate, endDate, unitNo, streetName, city;
static int contactNo, noClasses, hoursWorked, noStudents, postcode, select;
static double annualSalary, hourlyRate;
public static void main(String[] args){
//menu looping
do{
System.out.println("=======================");
System.out.println("| Main Menu |");
System.out.println("| Select an option |");
System.out.println("| 1. Lecturer |");
System.out.println("| 2. Class Info |");
System.out.println("| 3. File Actions |");
System.out.println("| 0. Exit |");
System.out.println("=======================");
select = scan.nextInt();
switch(select){
case 1:
lecturerMenu();
break;
case 2:
classInfoMenu();
break;
case 3:
fileMenu();
case 0:
System.out.println("Exiting...");
System.exit(0);
break;
default:
System.out.println("Error please select again");
}
}while(select !=0);
}
Eventually it will make its way to the part where the user adds part time lecturer data. the set is incomplete as i didnt know how to do the addresspart
public static void newPartTime(){
System.out.println("Enter Part Time Lecturer Details");
System.out.print("Enter Staff Number: ");
scan.nextLine();
staffNo = scan.nextLine();
System.out.print("Enter Name: ");
name = scan.nextLine();
System.out.print("Enter Contact Number: ");
contactNo = scan.nextInt();
System.out.print("Enter Hourly Rate: ");
hourlyRate = scan.nextDouble();
System.out.print("Enter Hours Worked: ");
hoursWorked = scan.nextInt();
System.out.println("Enter Address");
System.out.print("Enter Unit Number: ");
scan.nextLine();
unitNo = scan.nextLine();
System.out.print("Enter Street Name: ");
streetName = scan.nextLine();
System.out.print("Enter City: ");
city = scan.nextLine();
System.out.print("Enter Postcode: ");
postcode = scan.nextInt();
scan.nextLine();
if(classI == null){
System.out.println("There is no class available. Please add a new class");
newClassInfo();
}else{
pt.setStaffNo(staffNo);
pt.setName(name);
pt.setContactNo(contactNo);
pt.setNoClasses(noClasses);
pt.set
}
}
}
Normally I would do this for my declaration:
static FullTime ft = new FullTime(var1, var1 ,var3, address);
Am I able to recreate the object or should I just add a method for set address in part time?
You could create an Object of the address class and set values to that and then set the object into your part time object.

My program is printing only the last input from the ArrayList

I have another small class containing the main method that display the
invoice, but the toString method here is only displaying the last item
entered, not the three itemnames,quantities, prices and totalPrice.
I have doubts about addItemLine and toString.
Can someone see what I am missing here?
I was enable to past the lineItem class code.
import java.util.ArrayList;
import java.util.Scanner;
public class Transaction {
private ArrayList<lineItem> lineItems;
private int customerID;
private String customerName;
public Transaction (int customerID, String customerName){
this.customerID= customerID;
this.customerName= customerName;
this.lineItems= new ArrayList<>();
}
public int getcustomerID(){
return customerID;
}
public void setcustomerID(int customerID){
this.customerID = customerID;
}
public String getcustomerName(){
return customerName;
}
public void setcustomerName(String customerName){
this.customerName = customerName;
}
public ArrayList addItemLine(lineItem line){
Scanner mykey=new Scanner(System.in);
for (int i=0; i<2;i++){
String k= line.getItemName();
int m= line.getQuantity();
double d= line.getPrice();
System.out.println("enter item name:");
k = mykey.next();
line.setItemName(k);
System.out.println("enter quantity:");
m= mykey.nextInt();
line.setQuantity(m);
System.out.println("enter unit price:");
d= mykey.nextDouble();
line.setPrice(d);
line.getItemName(); line.getQuantity(); line.getPrice();
lineItems.add(new lineItem(k,m,d));
}
return this.lineItems;
}
public void updateItem(String item, int quant, double pri){
lineItem l= new lineItem(item, quant, pri);
int m=0;
m= l.getQuantity();
m=m+quant;
double tot=0;
}
public double getTotalPrice(){
double totalPrice = 0;
for (int i =0;i<2; i++){
lineItem item = lineItems.get(i);
totalPrice = totalPrice + item.getTotalPrice();
}
return totalPrice;
}
public String getLineItem( String s, int d, double k){
lineItem o= new lineItem(s,d,k);
for (int i =0;i<2; i++){
if (!s.equals(o.getItemName()))
System.out.println("item not found");
else
s= (o.getItemName() + o.getQuantity() + o.getPrice());
}
return s;
}
public String toString(lineItem lin) {
String a="", b="";
a=("Customer ID:" + this.getcustomerID() + "\n" + "Customer Name: " +
this.getcustomerName());
for (int i=0; i<2;i++){
b= ("\n\n" + lin.getItemName() + "\t" + "Qty" + lin.getQuantity() + "
"
+ "#" + lin.getPrice() + " "+ "\t" + "$" + lin.getTotalPrice());
}
return a + b;
}
TransactionTesting:
import java.util.Scanner;
public class TransactionTesting {
public static void main(String args[]) {
String m=""; int g=0; double r=0; int id=0; String name="";
Scanner mykey= new Scanner(System.in);
System.out.println("enter customer name:");
name= mykey.nextLine();
System.out.println("enter customer ID:");
id=mykey.nextInt();
Transaction mytrans= new Transaction(id, name);
lineItem line= new lineItem(m,g,r);
mytrans.addItemLine(line);
System.out.println(mytrans.toString(line));
}
}
Change your toString() method like this:
public String toString() {
String a="", b="";
a=("Customer ID:" + this.getcustomerID() + "\n" + "Customer Name: " +
this.getcustomerName());
for (lineItem item : this.lineItems)
b += ("\n\n" + item.getItemName() + "\t" + "Qty" + item.getQuantity() + " "
+ "#" + item.getPrice() + " "+ "\t" + "$" + item.getPrice());
return a + b;
}
and from your test class call this method as the following:
System.out.println(mytrans.toString());
You don't need any argument in order to print your entire list.
Try to refactor your code a bit. It works, but it can be written better and better ;)
1) The call
System.out.println(mytrans.toString(line));
is printing out the single lineitem that is passed to it. What you probably intended was for Transaction.toString() to iterate over its list Transaction.lineItems and print each item in turn.
In fact Transaction.toString() doesn't need to take in a lineItem argument, the method should merely print out the internals of the class instance.
2) There is a similar confusion in Transacton.addItemLine(). It accepts a lineItem, prompts the user for new values, updates lineItem.. then constructs a new lineItem to store in Transaction.lineItems. It isn't actually causing a bug that I can see but you should get rid of the lineItem argument entirely; addItemLine doesn't need it.
3) Incidentally:
for (int i=0; i<2;i++){ }
loops twice, not three times. I trust you would have caught that in testing.
4) There is also a line of code near the end of addItemLine that doesn't actually do anything! Maybe you can spot that one on your own.
There are some other issues but those are the ones that leapt out at me.
Just a quick non-tested solution that may work. Something is copied from your code, something is changed because your code was wrong.
// If you create this inside the method than you'll lose everything everytime you call addItemLine
private ArrayList<lineItem> lineItems;
public void addItemLine(lineItem line){
Scanner mykey=new Scanner(System.in);
for (int i=0; i<2;i++){
String k= line.getItemName();
int m= line.getQuantity();
double d= line.getPrice();
System.out.println("enter item name:");
k = mykey.next();
line.setItemName(k);
System.out.println("enter quantity:");
m= mykey.nextInt();
line.setQuantity(m);
System.out.println("enter unit price:");
d= mykey.nextDouble();
line.setPrice(d);
line.getItemName(); line.getQuantity(); line.getPrice();
lineItems.add(new lineItem(k,m,d));
// This doesn't have to return anything, it just adds to the list
}
// No parameteres, this should build the string for the current object
public String toString() {
// String concatenation is not the best idea, StringBuilder is better
StringBuilder sb = new StringBuilder();
// If you want to print all of them then you need to iterate over the list
for (lineItem item : lineItems){
sb.append("Customer ID:" + this.getcustomerID() + "\n" + "Customer Name: " + this.getcustomerName());
for (int i=0; i<2;i++){
// Copied from your code
sb.append("\n\n" + lin.getItemName() + "\t" + "Qty" + lin.getQuantity() + " "+ "#" + lin.getPrice() + " "+ "\t" + "$" + lin.getTotalPrice());
}
sb.append("\n);
}
return sb.toString();
}
It seems that you don't understand how to create a Java object, or how to keep your application model separate from your application view.
Here's a test run of your code, after I made some changes.
Enter customer name: Gilbert
Enter customer ID: 123
Enter item name: Spinach
Enter quantity: 5
Enter unit price: .89
Customer ID: 123
Customer Name: Gilbert
Spinach Qty 5 #0.89 $4.45
Enter item name: Corn
Enter quantity: 12
Enter unit price: .29
Customer ID: 123
Customer Name: Gilbert
Corn Qty 12 #0.29 $3.4799999999999995
Enter item name:
First, let's look at your Java objects. The first Java object which you didn't include, is LineItem. Note that Java class names start with a capital letter.
package com.ggl.transaction;
public class LineItem {
private String itemName;
private int quantity;
private double price;
public LineItem(String itemName, int quantity, double price) {
this.itemName = itemName;
this.quantity = quantity;
this.price = price;
}
public String getItemName() {
return itemName;
}
public void setItemName(String itemName) {
this.itemName = itemName;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public double getTotalPrice() {
return price * quantity;
}
}
A Java object consists of class fields, and getters and setters for the fields.
Next, here's your Transaction class.
package com.ggl.transaction;
import java.util.ArrayList;
import java.util.List;
public class Transaction {
private List<LineItem> lineItems;
private int customerID;
private String customerName;
public Transaction(int customerID, String customerName) {
this.customerID = customerID;
this.customerName = customerName;
this.lineItems = new ArrayList<>();
}
public int getcustomerID() {
return customerID;
}
public void setcustomerID(int customerID) {
this.customerID = customerID;
}
public String getcustomerName() {
return customerName;
}
public void setcustomerName(String customerName) {
this.customerName = customerName;
}
public void addItemLine(LineItem line) {
this.lineItems.add(line);
}
public void updateItem(String item, int quant, double pri) {
LineItem l = new LineItem(item, quant, pri);
int m = 0;
m = l.getQuantity();
m = m + quant;
l.setQuantity(m);
}
public double getTotalPrice() {
double totalPrice = 0;
for (int i = 0; i < 2; i++) {
LineItem item = lineItems.get(i);
totalPrice = totalPrice + item.getTotalPrice();
}
return totalPrice;
}
public String getLineItem(String s, int d, double k) {
LineItem o = new LineItem(s, d, k);
for (int i = 0; i < 2; i++) {
if (!s.equals(o.getItemName()))
System.out.println("item not found");
else
s = (o.getItemName() + o.getQuantity() + o.getPrice());
}
return s;
}
public String toItemString(LineItem lin) {
String b = "";
String a = ("Customer ID: " + this.getcustomerID() + "\n"
+ "Customer Name: " + this.getcustomerName());
for (int i = 0; i < 2; i++) {
b = ("\n\n" + lin.getItemName() + "\t" + "Qty " + lin.getQuantity()
+ " " + "#" + lin.getPrice() + " " + "\t" + "$"
+ lin.getTotalPrice() + "\n");
}
return a + b;
}
}
I simplified your addItemLine class. Code that receives input using the Scanner class belongs in your TransactionTesting class.
I renamed your toString method to toItemString. toString is a method of the Object class. Since your method has a parameter, I renamed it to lessen any confusion.
Finally, here's your TransactionTesting class. I fixed it up so it would work. You can specify any number of line items. To stop processing, just enter a blank item name.
package com.ggl.transaction;
import java.util.Scanner;
public class TransactionTesting {
public static void main(String args[]) {
Scanner mykey = new Scanner(System.in);
System.out.print("Enter customer name: ");
String name = mykey.nextLine().trim();
System.out.print("Enter customer ID: ");
int id = Integer.valueOf(mykey.nextLine().trim());
Transaction mytrans = new Transaction(id, name);
boolean processing = true;
while (processing) {
System.out.print("Enter item name: ");
String k = mykey.nextLine().trim();
if (k.equals("")) {
processing = false;
} else {
System.out.print("Enter quantity: ");
int m = Integer.valueOf(mykey.nextLine().trim());
System.out.print("Enter unit price: ");
double d = Double.valueOf(mykey.nextLine().trim());
LineItem lineItem = new LineItem(k, m, d);
mytrans.addItemLine(lineItem);
System.out.println("\n" + mytrans.toItemString(lineItem));
}
}
mykey.close();
}
}
Remember, keep your application model (LineItem & Transaction) separate from your application view (TransactionTesting).
Simply put, in your method "addItemLine" you take data from 1 lineItem, overwrite it with some keyboard input, and the put in the list 2 other lineItem instances.
Then in the test code you print the original lineItem, which is not even in the list.
The method itself iterates on nothing, just creates twice the same string "b".
I suggest you to look at some tutorials on arrays and for loops.

Inheritance code returns no value

I created a super class called Employee, with a subclass called ProductionWorker and a driver called ProductionWorkerDriver. The program takes my entered info and returns the String values from the Employee class, but not the double and int values from the ProductionWorker class. The program I'm using said I had to initialize the values of those as 0, and I'm thinking that's why they show up as zero when compiled. However, the program won't compile without that, so I'm not sure what to do.
public class Employee {
private String name;
private String employeeNumber;
private String hireDate;
public Employee(String n, String num, String date) {
name = n;
employeeNumber = num;
hireDate = date;
}
public Employee() {
name = "";
employeeNumber = "";
hireDate = "";
}
public void setName(String n) {
name = n;
}
public void setEmployeeNumber(String e) {
employeeNumber = e;
}
public void setHireDate(String h) {
hireDate = h;
}
public String getName() {
return name;
}
public String getEmployeeNumber() {
return employeeNumber;
}
public String getHireDate() {
return hireDate;
}
public String toString() {
String str = "Employee Name: " + name
+ "\nEmployee #: " + employeeNumber
+ "\nHire Date: " + hireDate;
return str;
}
} //end of Employee class
//beginning of ProductionWorker class
import java.text.DecimalFormat;
public class ProductionWorker extends Employee {
private int shift;
private double payRate;
public int DAY_SHIFT = 1;
public int NIGHT_SHIFT = 2;
public ProductionWorker(String n, String num, String date, int sh, double rate) {
super(n, num, date);
shift = sh;
payRate = rate;
}
public ProductionWorker() {
}
public void setShift(int s) {
shift = s;
}
public void setPayRate(double p) {
payRate = p;
}
public int getShift() {
return shift;
}
public double getPayRate() {
return payRate;
}
public String toString() {
DecimalFormat dollar = new DecimalFormat("#,##0.00");
String str = super.toString() + "\nShift: " + shift
+ "\nPay Rate: $" + dollar.format(payRate);
return str;
}
}//end of ProductionWorker class
//beginning of ProductionWorkerDriver
import java.util.Scanner;
public class ProductionWorkerDriver {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
String name = null;
String employeeNumber = null;
String hireDate = null;
int shift = 0;
double payRate = 0;
int DAY_SHIFT = 1;
int NIGHT_SHIFT = 2;
Employee info = new Employee(name, employeeNumber, hireDate);
System.out.println("Employee Name:");
name = keyboard.nextLine();
System.out.println("Employee #:");
employeeNumber = keyboard.nextLine();
System.out.println("Hire Date:");
hireDate = keyboard.nextLine();
ProductionWorker info2 = new ProductionWorker(name, employeeNumber, hireDate, shift, payRate);
System.out.println("Shift 1 or 2:");
shift = keyboard.nextInt();
System.out.println("Pay Rate:");
payRate = keyboard.nextDouble();
System.out.println(info2.toString());
}
}//end of ProductionWorkerDriver
You're not doing anything with the data you've entered:
System.out.println("Shift 1 or 2:");
shift = keyboard.nextInt();
System.out.println("Pay Rate:");
payRate = keyboard.nextDouble();
... the shift and payRate variables aren't used again. Changing the values of these local variables doesn't change the values in the instance that you created earlier using the same variables.
You should either be calling:
info2.setShift(shift);
info2.setPayRate(payRate);
... or better, wait until after you've asked those questions before you construct the instance. You're also not using your info variable at all. Your entire main method can be improved to:
Scanner keyboard = new Scanner(System.in);
System.out.println("Employee Name:");
String name = keyboard.nextLine();
System.out.println("Employee #:");
String employeeNumber = keyboard.nextLine();
System.out.println("Hire Date:");
String hireDate = keyboard.nextLine();
System.out.println("Shift 1 or 2:");
int shift = keyboard.nextInt();
System.out.println("Pay Rate:");
double payRate = keyboard.nextDouble();
ProductionWorker worker =
new ProductionWorker(name, employeeNumber, hireDate, shift, payRate);
System.out.println(worker);
Notice how in each case we don't declare a variable until we need it.
Note that the fact that your employee number and your hire date are both String values is a bit of a worry, and it's a bad idea to use double for currency values - get into the habit of using BigDecimal, or use an integer to represent a number of cents/pennies/whatever.
This:
System.out.println("Shift 1 or 2:");
shift = keyboard.nextInt();
System.out.println("Pay Rate:");
payRate = keyboard.nextDouble();
Will update the shift and payRate of your main method:
public static void main(String[] args)
{
//...
int shift = 0;
double payRate = 0;
Because you're outputting the values from the ProductionWorker, and those values are never updated, it will always output 0. Simply because you initialize ProductionWorker with those variables does not mean that the reference shift in the main method will point to the same place in memory as the reference shift inside ProductionWorker.

Input skipped when using a scanner for text containing spaces

I was tasked with creating a small application for college, and have created a simple booking system.
I'm having an issue in that when the program runs, for no reason I can fathom it's executing the print part of a method but then jumping to the next method without executing the in.next() part of the original method.
I've included here in order the abstract class, the class where the issue is occurring, the menu, and the 'Creation' class.
I've been informed before here my coding (at least naming conventions) are not the best so I apologize for this in advance.
When I altered the class so that wasn't an extension of raw_Booking it seemed to not have this issue but not sure if that's relevant.
import java.util.Scanner;
abstract class raw_Booking {
private static String fname;
private static String lname;
private static int HouseNo;
private static String Street;
private static String Postcode;
Scanner in = new Scanner(System.in);
raw_Booking(){
}
abstract public String Setfname();
abstract public String Setlname();
abstract public int SetHouseNo();
abstract public String SetStreet();
abstract public String SetPostcode();
abstract public String Verification();
}
The problem class (method is SetPostcode):
import java.util.Scanner;
import java.io.*;
class Hotel_Booking extends raw_Booking{
Scanner in = new Scanner(System.in);
private String TheVerification;
private int guests;
private String Roomtype;
private double numbRooms;
private double costStay;
private double nights;
private static String fname;
private static String lname;
private static int HouseNo;
private static String Street;
private static String Postcode;
Hotel_Booking() {
fname = Setfname();
lname = Setlname();
HouseNo = SetHouseNo();
Street = SetStreet();
Postcode = SetPostcode();
TheVerification = Verification();
Roomtype = setRoomtype();
guests = guests();
numbRooms = numbRooms();
nights = nights();
costStay = costStay();
Write_File();
}
public String Setfname(){
System.out.println();
System.out.print("Bookers first name please: ");
fname = in.next();
return fname;
}
public String Setlname(){
System.out.println();
System.out.print("Bookers surname please: ");
lname = in.next();
return lname;
}
public int SetHouseNo(){
Scanner sc = new Scanner(System.in);
System.out.println();
System.out.print("Please enter your house number: ");
while (!sc.hasNextInt()) {
System.out.println();
System.out.print("You need to enter a number - please re-enter: ");
sc.next();
}
return sc.nextInt();
}
public String SetStreet(){
System.out.println();
System.out.print("Please enter your street: ");
Street =in.next();
return Street;
}
public String SetPostcode(){
System.out.println();
System.out.print("Please enter your postcode: ");
Postcode = in.next();
return Postcode;
}
public String Verification(){
System.out.println();
System.out.print("Please provide your car reg as verification: ");
TheVerification = in.next();
return TheVerification;
}
public String setRoomtype(){
System.out.println();
System.out.print("Would you like a Premiun or Regular room(s)? ");
Roomtype = in.next();
return Roomtype;
}
public int guests(){
System.out.println();
System.out.print("How many guests will be staying? ");
guests = in.nextInt();
return guests;
}
//For every 3 guests their must be 1 room at £50 per night.
//Premiun rooms = price doubled
public double numbRooms(){
for(int i=0;i < guests;i++){
numbRooms = numbRooms+1;
i = i + 2;
}
System.out.println();
System.out.println("You will require " + numbRooms + " number of rooms");
return numbRooms;
}
public double nights(){
System.out.println();
System.out.print("How many nights are you staying? ");
nights = in.nextDouble();
return nights;
}
public double costStay(){
if(Roomtype.equals("Regular")){
costStay = (nights * numbRooms)*50;
}
else{
costStay = (nights * numbRooms)*100;
}
System.out.println();
System.out.println("The total cost of your stay will be: " + costStay);
return costStay;
}
public void Write_File(){
System.out.println();
System.out.println("Your details will now be written to file.");
System.out.println();
try{
PrintWriter wr = new PrintWriter(new FileOutputStream("Hotel_Booking.txt",true));
wr.println("Name: " + fname+ " " + lname);
wr.println("Address line one: " + HouseNo + " " + Street);
wr.println("Postcode: " + Postcode);
wr.println("Roomtype: " + Roomtype);
wr.println("Number of rooms: " + numbRooms);
wr.println("Nights staying: " + nights);
wr.println("Total cost of stay: " + costStay);
wr.close();
}
catch (IOException e){
System.out.println("Error -- " + e.toString());
}
}
public static String Getfname(){
return fname;
}
}
Contains Interface/Menu.
public class Interface{
public static void Menu(){
System.out.println("Welcome to the booking system select an option");
System.out.println("1 - Create a new hotel booking");
System.out.println("2 - Create a new airline booking");
System.out.println("3 - Create a car hire booking");
System.out.println("4 - Create a amusement park ticket booking");
System.out.println("5 - Create a concert ticket booking");
System.out.println();
}
}
Main point of execution:
import java.util.ArrayList;
import java.util.Scanner;
public class Booking_Creation{
static Scanner in = new Scanner(System.in);
static ArrayList<Hotel_Booking> hotelbookings = new ArrayList<Hotel_Booking>();
static ArrayList<Flight_Booking> flightbookings = new ArrayList<Flight_Booking>();
static ArrayList<Car_Hire> carhirebookings = new ArrayList<Car_Hire>();
static ArrayList<Amusement_Park_Ticket> parkticket = new ArrayList<Amusement_Park_Ticket>();
static ArrayList<Concert_Ticket> concertticket = new ArrayList<Concert_Ticket>();
static int selection;
public static void main(String[] arguments){
Interface.Menu();
selection = in.nextInt();
// COULD ASK THE QUESTIONS HERE????
/// BUT THE INPUT BIT IS INSIDE THE OTHER CLASS
switch(selection){
case 1:
Hotel_Booking hb = new Hotel_Booking();
hotelbookings.add(hb);
break;
case 2:
Flight_Booking fb = new Flight_Booking();
flightbookings.add(fb);
break;
case 3:
Car_Hire ch = new Car_Hire();
carhirebookings.add(ch);
break;
case 4:
Amusement_Park_Ticket pt = new Amusement_Park_Ticket();
parkticket.add(pt);
break;
case 5:
Concert_Ticket ct = new Concert_Ticket();
concertticket.add(ct);
break;
}
}
}
Example output:
Welcome to the booking system select an option
1 - Create a new hotel booking
2 - Create a new airline booking
3 - Create a car hire booking
4 - Create a amusement park ticket booking
5 - Create a concert ticket booking
1
Bookers first name please: Herton
Bookers surname please: Ferford
Please enter your house number: 4
Please enter your street: Park Lane
Please enter your postcode:
Please provide your car reg as verification: KS23
After a quick glance to your sample execution, I think that the street name is parsed as two tokens, so the street name is set as "Tulloch" and when prompted for the postcode (as a string), "Park" is read.
It might be useful to set a pattern on the Scanner.next() method to force a full line as a single token ?

Categories