What I have below is producing the desired results by print some employee details along with weekly / monthly wages as appropriate.
However I understand that I should not be inputting data in the constructor as I've done.
I need to prompt for a hours worked value only for "PartTimeEmployees", just not the way I've done it.
I've tested with For-Each loops, Enhanced For loops and using the instanceOf operator.
If I could get some guidance/hints or examples of how to accomplish what is currently being done in the constructor, but in the TestEmployee class instead that would be great.
Mostly I'm not sure how to even describe what I'm trying to achieve. This hinders Googling somewhat. (Help with a better title would also be great)
Thanks in advance.
public class TestEmployee
{
public static void main(String[] args)
{
int size;
Employee[] employees = new Employee[4];
employees[0] = new FullTimeEmployee("Jane", 26000);
employees[1] = new PartTimeEmployee("Jack");
employees[2] = new FullTimeEmployee("Lucy", 52000);
employees[3] = new PartTimeEmployee("Lenny");
for(int i = 0; i < employees.length; i++)
{
employees[i].print();
}
}
}
Class: PartTimeEmployee - Constructor:
public PartTimeEmployee(String thisName)
{
super(thisName);
System.out.println("Please enter the number of hours worked by " + thisName + ": ");
numHours = keyboard.nextInt();
setHours(numHours);
}
If I get your question, below might fit with your need -
First of all create generic Employee class -
class Employee {
private String name;
private int workingHours;
private final boolean IS_PART_TIME_EMP;
public Employee(String name, int workingHours) {
this.name = name;
this.workingHours = workingHours;
this.IS_PART_TIME_EMP = false;
}
public Employee(String name) {
this.name = name;
this.IS_PART_TIME_EMP = true;
}
public String getName() {
return name;
}
public int getWorkingHours() {
return workingHours;
}
public void setWorkingHours(int workingHours) {
this.workingHours = workingHours;
}
public boolean isPartTimeEmployee() {
return IS_PART_TIME_EMP;
}
}
Now you can use it as per your requirement.
Employee[] employees = new Employee[4];
employees[0] = new Employee("Jane", 26000);
employees[1] = new Employee("Jack");
employees[2] = new Employee("Lucy", 52000);
employees[3] = new Employee("Lenny");
Scanner sc = new Scanner(System.in);
for (Employee employee : employees) {
if(employee.isPartTimeEmployee()) {
System.out.println("Please enter working hours by " + employee.getName() + ": ");
int numHours = sc.nextInt();
employee.setWorkingHours(numHours);
}
}
Constructor is not meant for user input.Its main intention is to initialize object of that class.
Instead of doing that in constructor,you can try something like this
employees[1] = new PartTimeEmployee("Jack");
System.out.println("Please enter the number of hours worked by " + employees[1].getName()+ ": ");
numHours = keyboard.nextInt();
employees[1].setHours(numHours);
You most likely will have some logical main loop in your program, like
while(!quit) {
// 1. ask if you want to add part time or full time employee
// 2. ask proper questions
// 3. call correct constructor
}
Writing such small pseudo code algorithm should be self explanatory and get you going.
Step one: presentation of options available for user and reading user input.
Step two: performing actions depending on user input from step 1
Step three: final call to proper constructor depending on results from steps 1 and 2
If I understood your question correctly (which I'm really not sure of) you want to prompt for the employee data in the main method.
In that case I'd use a loop and query the following things:
name of the employee
does the employee work full time? (y/n)
if yes: what is the wage? (assume hours = whatever a full time employee works a day)
if no: how many hours? (and probably the hourly wage as well)
Then use that information to construct an Employee object (I don't see any need for the subclasses here).
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());
}
So I've been given the method below and I'm not allowed to change it. What I need is it to create a couple of objects with the variables below but keeps coming up with an error that says "The constructor menu(int, String, String) is undefined." Am I doing something wrong?
import java.util.Scanner;
import java.util.*;
public class menu {
private static void addNewStudent()
{
Scanner scanner = new Scanner(System.in);
System.out.println("Please enter the correct details below");
System.out.println("ID: ");
int userId = scanner.nextInt();
System.out.println("First name: ");
String userFirst = scanner.next();
System.out.println("Last name: ");
String userLast = scanner.next();
System.out.println("English assignment 1 mark: ");
int english1 = scanner.nextInt();
System.out.println("English assignment 2 mark: ");
int english2 = scanner.nextInt();
System.out.println("English assignment 3 mark: ");
int english3 = scanner.nextInt();
System.out.println("Math assignment 1 mark: ");
int math1 = scanner.nextInt();
System.out.println("Math assignment 2 mark: ");
int math2 = scanner.nextInt();;
System.out.println("Math assignment 3 mark: ");
int math3 = scanner.nextInt();
menu userStudentObj = new menu(userId, userFirst, userLast);
menu userEnglishObj = new menu(english1, english2, english3);
menu userMathObj = new menu(math1, math2, math3);
// Asks the user for the student information (ID, First, Last, Assignments)
// Then creates the appropriate objects and adds the students to the student list
I would expect to have created 3 new object that contain the user input variables within the objects if that makes sense.
The main problem is that you didn't specify any non default constructor, to create objects so compiler have no ideas what do you want to create if object is not specified for that. But there is another problem. Your object is designed in not the best way. So if you want to handle it correctly you could change your class design so you handle it in right way.
For example you could make it a bit different, like in this example (it's not perfect, it still can be more separate and better designed):
class User {
int userId;
String userFirstName;
String userSecondName;
private ArrayList<Integer> mathSums = new ArrayList<>();
private ArrayList<Integer> englishSums = new ArrayList<>();
User(int userId, String userFirstName, String userSecondName) {
this.userId = userId;
this.userFirstName = userFirstName;
this.userSecondName = userSecondName;
}
public void addMathSums(int mathSums) {
this.mathSums.add(mathSums);
}
public void addEnglishSums(int englishSums) {
this.englishSums.add(englishSums);
}
}
So by the help of this class you could change the way, how you define and set the values for your object and it would look like that:
1) You define constructor with arguments so you're able to use it for object creation:
User user = new User(userId, userFirst, userLast);
2) Then you can add sums into ArrayLists that are member variables (fields) in User class:
user.addMathSums(math1);
user.addMathSums(math2);
user.addMathSums(math3);
user.addEnglishSums(english1);
user.addEnglishSums(english2);
user.addEnglishSums(english3);
It could be performed in different ways using arrays, lists or other data structure, but you really need to pay attention for your class design. More time you spend on designing object less modifications you will need later.
3) You probably want to interact with this object so you need to get a reference for it somehow. You could change the method signature so you will "return" created object after you finish your input. So you need to make some changes:
On the method change the signature return type to User:
private static User addNewStudent() { ... }
Then add return for that and return created user:
private static User addNewStudent() {
/* code */
User user = new User(userId, userFirst, userLast);
/* add sums */
return user;
}
4) Use this method in your main():
public static void main(String[] args) {
User createdUser = User.addNewStudent();
}
I am trying to make an erase function to delete the teams of the tournament using the team code (value c in the constructor). Firstly I want to check if that team exists in the objects I made in the main method. Is that possible to do that using an if statement?
Exercise:
Create a java application that stores data for various football teams. Each team has a name, a code and the current points in the championship. In your class create methods for registering new teams, erasing existing teams using their code and showing a list for all the teams currently active in the championship
package assignment.exercise4;
public class Data {
private String name = "";
private int code = 0;
private static int register;
private int erase;
private int currentpoints = 0;
public Data(int c, int points, String n) { //constructor
code = c;
this.currentpoints = points;
name = n;
}
public void Erase(int c)
{
code = c;
if(code != 0)
System.out.println("Team with Code: "+code+" has been erased" );
else
System.out.print("Team with code "+code+" does not exist!");
}
public void Register(String newTeam,int code)
{
name = newTeam;
this.code = code;
System.out.println("New Team " + name + " registered with code " + code);
}
public void print()
{
System.out.println("Team name: " + name + "\nTeam code: " + code + "\nTeam points: " + currentpoints + "\n");
}
}
/*
public static void main(String[] args) {
System.out.println("\nList of Teams: \n");
Data t1 = new Data(110,42,"Juventus");
Data t2= new Data(105,45,"Manchester City");
Data t3= new Data(240,50,"Barcelona");
Data t4= new Data(122,36,"Arsenal");
Data Team = new Data(0,0,""); //use for erase
t1.print();
t2.print();
t3.print();
t4.print();
System.out.println("Teams erased: \n");
Team.Erase(110);
Team.Erase(122);
Team.Erase(0);
System.out.println("\n\nTeams Registered: \n");
t1.Register("Real madrid", 11);
t1.Register("Atletico Madric", 112);
}
}
*/
What are you trying to erase the teams from?
If they were in a list, for example...
Data t1 = new Data(110,42,"Juventus");
Data t2= new Data(105,45,"Manchester City");
Data t3= new Data(240,50,"Barcelona");
Data t4= new Data(122,36,"Arsenal");
List<Data> teams = Arrays.asList(t1, t2, t3, t4);
...you could create a list with a team erased like this...
public List<Data> erase(List<Data> team, int id) {
return team.stream()
.filter(t -> t.getId() != id)
.collect(Collectors.toList());
}
So...
List<Data> remainingTeam = erase(team, 122); // Removes Arsenal
...would remove the first element from the list
I will not answer this to elaborately since it is homework. I will try to give you a hint though.
If you have a team and want to do something with it. Otherwise you just have a team which just stays there in a particular scope (if you do not know what scope is, look it up!). If you have a team you most likely want do do something with it. In this case you seem to want to store information about the teams to use in a championship. Important to note here is that the teams are not the focus here. The real focus is the Championship. The teams are just a part of the championship. There can still be a championship even if all teams does not choose to participate. But you want all teams choosing to participate to be registered to this particular championship (eg UEFA Champions League).
This leads to something called aggregate or association depending on how hard you want to tie the object to the championship. However you do probably not need to pursue these terms any further at this point. What is important to remember is that there is an "has a" relation between the championship and the teams. The championship "has a" collection of participating teams. This is normally reflected in this way in code,
public class Championship {
private Team[] teams; // Or List<Team>, Collection<Team>, HashMap<Team>, ...
}
The Championship can then have methods for registering a team, removing a team, updating status, etc...
public void register(Team t) {
if (numberOfTeams < teams.length) {
teams[numberOfTeams] = t; // Index starts at zero
numberOfTeams++;
} else {
throw new IndexOutOfBoundsException("The list is full. " +
"No more teams may be registered!")
}
}
Even though the function erasing a team was requested, I believe I will not write it down. This design is so different from your original intent, so that writing the erase function will likely solve your complete homework. However, you do actually not have to erase the team it is perfectly possible to just overwrite the position with the next team as,
teams[i] = teams[i+1];
Hope this helps!
Short answer:
public void erase(int id) {
// who needs an if statement, if we can use predicates?
teams.removeIf(team -> team.getId() == id);
}
But this will not work with your current code. Your current code misses the container for your teams.
Longer answer:
For the fun of it. Solving your homework:
class Team {
int id;
String name;
int points;
Team(int id, String name, int points) {
this.id = id;
this.name = name;
this.points = points;
}
#Override
public String toString() {
// ugly formatted... another homework? ;-)
return "Team '" + name + "' (" + id + "): " + points;
}
}
Note, that I will not add any getter or setter, nor will I care about visibility here. I will leave that as another homework for you.
class Championship {
List<Team> teams = new ArrayList<>();
void register(Team team) {
teams.add(team);
}
void erase(int id) {
teams.removeIf(team -> team.id == id);
}
#Override
public String toString() {
// for additional fun... sorted by descending points
return "=== Championship table ===\n"
+ teams.stream()
.sorted((o1, o2) -> Integer.compare(o2.points, o1.points))
.map(Objects::toString)
.collect(Collectors.joining("\n"));
}
}
Somewhere else:
public static void main(String[] args) {
Championship championship = new Championship();
championship.register(new Team(1, "not the best ones", 3));
championship.register(new Team(2, "The better ones", 7));
championship.register(new Team(3, "The winners", 11));
System.out.println(championship);
championship.erase(3);
System.out.println(championship);
}
Output:
=== Championship table ===
Team 'The winners' (3): 11
Team 'The better ones' (2): 7
Team 'not the best ones' (1): 3
=== Championship table ===
Team 'The better ones' (2): 7
Team 'not the best ones' (1): 3
Too much of information? Just start with something like a championship-class or at least use a collection of Teams (e.g. List<Team>).
By the way... Do not deliver this solution as your homework, except you understand what is going on and you can explain it with your own words. Otherwise you are only betraying yourself.
I am running into some issues with my Java program. We have to create a library, which contains the title(halo, lotr) , the format (xbox, dvd etc), the date loaned (if it is ever loaned), and the person it is loaned to (if it is ever loaned).
I am not complete with my code, however I am testing it out as I go along instead of just compiling the entire finished code after 5 hours of coding. I am running into a problem. Whenever I set a public string variable to a value, it saves in the method I declared it in, but it will display "null" when system.out.print'd in other methods.
heres my code. First class is Library.
package p1;
import java.util.Scanner;
public class Library {
// \/ FIELDS
private String[] mediaItemTitle = new String[100];
public String[] mediaItemFormat = new String[100];
public String[] mediaItemLoanedTo = new String[100];
public String[] mediaItemOnLoan = new String[100];
public String[] mediaItemDateLoaned = new String[100];
public String today = "3/9/2015";
public int numberOfItems;
// /\ FIELDS
// \/ METHODS
public static void main(String[] brad){
Scanner input = new Scanner(System.in);
MediaItem main;
main = new MediaItem();
String title;
String format;
String date;
String name;
for ( int i = 0; i != 5; ){
i = displayMenu();
if (i == 1){
System.out.println("What is the title? ");
title = input.nextLine();
System.out.println("What is the format? ");
format = input.nextLine();
main.MediaItem(title,format);
}else if (i == 2){
System.out.println("Which Item (Enter the title? ");
title = input.nextLine();
System.out.println("Who are you loaning it to? ");
name = input.nextLine();
System.out.println("When did you loan it to them? ");
date = input.nextLine();
}else if (i == 3){
main.MediaItem();
}else if (i == 4){
System.out.print("Which item? (enter the title) ");
title = input.nextLine();
main.markReturned(title);
}else if (i == 5){ // DONE
System.out.print("Goodbye!");
break;
}
}
}
public static int displayMenu(){ // DONE
Scanner input = new Scanner(System.in);
int choice = 0;
System.out.println("1. Add new item");
System.out.println("2. Mark an item as on loan");
System.out.println("3. List all items");
System.out.println("4. Mark an item as returned");
System.out.println("5. Quit");
choice = input.nextInt();
return choice;
}
public void addNewItem(String title, String format){
this.mediaItemTitle[numberOfItems] = title;
this.mediaItemFormat[numberOfItems] = format;
System.out.print("TEST: " + mediaItemTitle[numberOfItems]);
}
public void incrementNumberOfItems(){
numberOfItems++;
}
public void listAllItems(){
for (int i = 0; i < numberOfItems; i++){
System.out.print(mediaItemTitle[i])
}
}
Here is the second part of code, my second class MediaItem
package p1;
public class MediaItem {
// \/ METHODS
public void MediaItem(){
Library list;
list = new Library();
list.listAllItems();
}
public void MediaItem(String title, String format){
Library call;
call = new Library();
call.addNewItem(title, format);
call.incrementNumberOfItems();
}
// /\ METHODS
}
This is driving me insane. I would love to just have me public variables save their value between methods but its not happening. the console (when 3 is chosen from displayMenu)
0
null
which means numberOfItems and mediaItemTitle[i] are read to be 0, and null. Which I dont understand, because I declared them earlier in the program!!!
I dont understand what Im doing wrong. please help me! Thank you!!
Your main mistake is that you are creating a new instance of Library inside your MediaItem method. That Library object will only live in the scope of MediaItem method. Plus Library is your main static class.
Your design is all wrong in my opinion. It looks like you are learning you way to Java or OOP, which is perfectly fine to have these mistakes.
Separate your data from your main class, create new classes just for your data. Have a look at java POJO (Plain Old Java Objects), like here
For example:
String title;
String format;
String date;
String name;
Should be in a new object, a POJO. Something like:
public class MyDataPOJO {
private String title;
private String format;
private String date;
private String name;
public MyDataPOJO(String title, String format, String date, String name) {
this.title = title;
this.format = format;
this.date = date;
this.name = name;
}
public String getTitle() {return title;}
public String getFormat() {return formate;}
// And the rest of the getter methods for date and name
}
In you Library class you may only need to hold your logic. But even that can be re-factored to another class.
On a side note, please check the java naming convention. Here is a guideline: link. In other words, start you methods name with lower case.
Example, your public void MediaItem(){/** something*/} should be public void mediaItem(){/** something*/ }
Follow the answer above and treat this as a comment, since the persons answer is correct and my statement isn't regarding your primary problem.
In your for-loop, I think you should add another else if statement. If the user enters a number that is not 1-5, they should receive an error. So maybe something like
else if (i < 1 || i > 5)
System.out.println("Error: Enter a choice 1-5\n");
Also, I think you may have forgotten a } to end your listAllItems() method.
But as I was saying, the answer to your real problem has already been handled, so give them the check mark. This is just a minor UI error I noticed.
public class Pig {
private int pigss;
private Pig[] pigs;
public Pig[] pigNumber (int pigss)
{
pigs = new Pig [pigss];
return pigs;
}
Code that includes main method:
public class animals{
public static void main(String[] args){
Pig cool = new Pig();
Scanner keyboard = new Scanner (System.in);
System.out.println("How many pigs are there?");
int pigss = Integer.parseInt( keyboard.nextLine() );
cool.pigNumber(pigss);
//This is where I have trouble. I want to use the array pigs here in the main method, this is what i tried:
Pig[] pigs = cool.pigNumber(pigss);
I then tried to use a for loop and assign values (String) to the index of arrays (pigs[]). But the error that gives me is: cannot convert from String to Pig. Any tips are appreciated. THank you.
for(int j = 0; j < pigs.length; j++)
{
System.out.println("What is the pig " + (j+1) + "'s name");
pigs[j] = keyboard.nextLine();
}
Your pigs will need an attribute to contain the string values you are trying to pass:
public class Pig {
private String name;
public void setName(String n) {
name = n;
}
public String getName() {
return name;
}
Then when you want to assign this string value to your pig:
int indexOfPig = 0; // Or whatever it is supposed to be
pigs[indexOfPig].setName("I am a string");
In java you can only use ints as the indexes of arrays
It is saying 'cannot convert from String to Pig' because you can't do that!
If you want somehow convert a String to a Pig, you are going to need to write some code to do the conversion. For example, you might write a constructor that creates a new Pig from some kind of description. Or you might write a method that looks up a Pig by name or number or something.
It is hard to offer any more concrete advice because you don't tell us what is in the string values ... or how you expect the strings to become pigs. (The only suggestion I have is to try Macrame :-) )
Pig doesn't have a name member or even method that accepts a string. Also you are trying to assign a String(keyboard.nextline() to a Pig(pigs[j].
Add an attribute name to your pig.
class Pig{
public String name:
public void Pig(String name){
this.name = name;
}
}
Then assign a new instance of Pig in the loop.
pigs[j] = new Pig(keyboard.nextLine());
Also get rid of the useless class pigNumber. All you need is an ArrayList of Pigs. The array list can be dynanically sized.
List<Pig> pigs = new ArrayList<Pig>
so your loop could be something like
String name = ""
while(true){
name = keyboard.readline();
if(name== "stop"){
break;
}
pigs.add(new Pig(names);
}
Then getting the number of pigs is a simple
System.out.println(pigs.length());