Homework - Providing Output F and other things - java

My task is to "design a class called employee that includes three instance variables, first name (string), last name (string), and monthly salary (double). Provide a constructor that initializes the threee instance variables. Provide set and get methods for each instance variable. [...] to get full credit, your programs should have no compilation errors and give correct outputs; they should also be well commented and appropriately formated."
Now, for all intents and purposes, this site helped me finish the shell of that homework yesterday, where I created the class, got the main to stop being annoying, initialized a constructor with 3 variables, and had set and get methods for them.
However, I also feel like I need to have some kind of actual instance variables that should be set'ed, get'ed, adn printf'ed out or something. Right now, the Command Prompt just self terminates on the first button press, because there's nothing for the program to actually DO.
In that way, I'm messing with my program as it will be displayed below. I can't quite get it to work, and would appreciate some insight into at least what I am doing wrong with the code below:
import java.util.Scanner;
public class Employee
{
public String FirstName, LastName; // String instance variables
public double Salary; //double floating-point instance variable
// main method begins program execution
public static void main( String[] args )
{
// create Scanner to enable user input in Dos
Scanner input = new Scanner(System.in );
}
// should introduce and initialize the constructor Employee
public Employee( String fName, String lName, double empSalary )
{
FirstName = fName;
LastName = lName;
Salary = empSalary;
}
// set First Name
public void setFirstName( String Steven ) // set the First Name
{
FirstName = Steven;
}
public void setLastName( String Dorsey ) // set the Last Name
{
LastName = Dorsey;
}
public void setSalary( double empSalary ) // set the Employee Salary
{
Salary = empSalary;
}
public String displayMessage()
{
// This statement calls Employee and should
// get the First Name from Input
System.out.printf( "Please enter the First Name\n");
getFirstName( string fName );
{
return FirstName;
}
System.out.printf( "Please enter the Last Name\n");
getLastName( string lName ) ); // get the Last Name
{
return LastName;
}
System.out.printf( "Salary: $%.2f\n");
getSalary( double empSalary )
{
return Salary;
}
}
} // End class
Now, here are my errors. provided this time by Textpad:
* Employee.java:54: error: ')' expected
getFirstName( string fName );
^
* Employee.java:54: error: illegal start of expression
getFirstName( string fName );
^
* Employee.java:60: error: ')' expected
getLastName( string lName ) ); // get the Last Name
^
* Employee.java:60: error: illegal start of expression
getLastName( string lName ) ); // get the Last Name
^
* Employee.java:60: error: ';' expected
getLastName( string lName ) ); // get the Last Name
^
* Employee.java:66: error: '.class' expected
getSalary( double empSalary )
^
* Employee.java:66: error: ';' expected
getSalary( double empSalary )

You don't have semicolons after your function names.
So, the following:
getLastName( string lName ) ); // get the Last Name
{
return LastName;
}
should instead be
getLastName( string lName ) ) // get the Last Name
{
return LastName;
}
Hope it helps, I didn't read through the rest of the code.

Your code shows that you probably have some misconceptions about how Java and programming languages in general work:
e.g. in the snippet:
public void setFirstName( String Steven ) // set the First Name
{
FirstName = Steven;
}
the naming of the String parameter Steven is very peculiar. Most programmers would name the parameter firstName or pFirstname because it holds a String variable. In some cases the content of that variable might be "Steven". Please note how I wrote the parameter names in bold while the variable content is put in quotes. The concepts variable and parameter are important to grasp before you'r code will function right. You might want to check your code along these lines for all the other concepts that you were asked to do in your assignment. Learning is about understanding the difference between a misconception and the right concept. Please don't get frustrated that your question got negative points. People on stackoverflow are expecting the people who ask questions to do the basic analysis of the problem themselves and then ask for help when they get stuck at a point where all the analysis didn't help.

try this:
public class Employee {
public String FirstName, LastName; // String instance variables
public double Salary; //double floating-point instance variable
//should introduce and initialize the constructor Employee
public Employee( String fName, String lName, double empSalary ) {
FirstName = fName;
LastName = lName;
Salary = empSalary;
}
public void setFirstName( String Steven ) // set the First Name
{
FirstName = Steven;
}
public void setLastName( String Dorsey ) // set the Last Name
{
LastName = Dorsey;
}
public void setSalary( double empSalary ) // set the Employee Salary
{
Salary = empSalary;
}
public String getFirstName()
{
return FirstName;
}
public String getLastName()
{
return LastName;
}
public double getSalary(){
return Salary;
}
public void displayEmployee(){
System.out.println("FirstName : "+FirstName);
System.out.println("LastName : "+LastName);
System.out.println("Salary : "+Salary);
}
//main method begins program execution
public static void main( String[] args )
{
// create Scanner to enable user input in Dos
Scanner input = new Scanner(System.in );
System.out.println("Enter employee details :");
Employee emp=new Employee(input.next(), input.next(), input.nextDouble());
emp.displayEmployee();
}
}// End of class

Related

Why do I get null as my output string instead of what I wanted?

I'm asked to compute a Java program with TestStaff that accepts name,
staff id and working perday as inputs from the user and displays the name, staff ID and salary of the staff. But at the end of the output, I got null null 0.0 . I'm a beginner at this object and class section and I'm really lost. Can anyone help? Here are my codes:
This is the given code:
class Staff {
private String name, staffID;
private double salary;
private int workingDay;
public void setStaffInfo(String nm, String id, int wDay){
name=nm;
staffID=id;
workingDay=wDay;
}
public void calculateSalary(){
salary = workingDay * 35.0;
}
public double getSalary(){
return salary;
}
public String getName(){
return name;
}
public String getStaffID(){
return staffID;
}
}
import java.util.Scanner;
Here are the codes for TestStaff:
class TestStaff {
static Scanner console = new Scanner(System.in);
public static void main(String arg[]){
Staff staff1= new Staff();
System.out.print("Enter your name: ");
String nm=console.nextLine();
System.out.print("Enter your Staff ID: ");
String id=console.nextLine();
System.out.print("Enter your working days: ");
int wDay=console.nextInt();
System.out.println(staff1.getName() + "\t" + staff1.getStaffID()+ "\t\t" + staff1.getSalary());
}
}
You need to use the Staff class set method to initialize its members.
i.e: staff1.setStaffInfo(nm, id, wDay);
What you've done is simply creating 3 new variables and assigning them values, but your Staff objects' members were not set.
Also you might want to call calculateSalary() before getSalary() because the former initializes the salary variable.
You are missing to call method staff1.setStaffInfo(nm, id, wDay);
I would suggest to have parameterized constructor with all the instance variables of class Staff, create instance for Staff using that constructor. That way you won't get null values.
Suggestion:
Create constructor in Staff class as:
Staff(){}
Staff(String name, String staffID, double salary , int workingDay){
this.name = name;
this.staffID=staffID;
this.salary=salary;
this.workingDay = workingDay;
}
And in TestStaff class, you can add these lines:
Staff staff2 = new Staff(nm,id, 2400, wDay);
System.out.println(staff2.getName() + "\t" + staff2.getStaffID() + "\t\t" + staff2.getSalary());
In the main method you have created the Staff object and stored all the input in some variable but haven't set the input in object. Thats why when you print staff1.getSalary() it returns you the default value of double i.e: 0.0. first set the value staff1.setInfo(...) And then print the values.
But at the end of the output, I got null, null, 0.0.
You are not passing any arguments to the setStaffInfo(String nm, String id, int wDay) anywhere in your code so that is why it is showing null, null,0.0
Solution
Pass the following variables to the setStaffInfo(String nm, String id, int wDay) method of the class Staff
String nm=console.nextLine();
String id=console.nextLine();
int wDay=console.nextInt();
Like this:
staff1. setStaffInfo(nm,id,wDay)
And an advice
Run your calculateSalary() in getSalary() method like this:
public double getSalary(){
calculateSalary(); //this will autimatically calculate salary
return salary;
}
Then, you will just have to call getSalary() in the main method and it will automatically call calculateSalary() or you can also put that one line of calculateSalary()in getSalary() also.
You create a new object from your Class Staff but you have to assign data member to the class and can done from 2 different ways :
1- Your method staff1.setStaffInfo(nm, id, wDay);
staff1.setStaffInfo(nm, id, wDay);
2- Constructor
Staff staff1= new Staff(id, nm, wDay);
Add the constructor below in Staff class this constructor will make you able to create a new object with specifying id, nm and wDay
Staff (String staffID ,String name , int workingDay) {
this.staffID = staffID;
this.name = name ;
this.workingDay = workingDay ;
}

How to reconstruct a name with a split String in Java?

First some info about my project,
I'm following a tutorial task where the main goal is to learn to work with error handling,
but I'm not at that part quite yet, I am working with establishing the main classes.
Thats what I need a little help and guidance with,(but errors are supposed to come up and be detected
so that I can learn to fix them later, but that's not the main question here, just information.)
Here's 3 of the classes which I've completed.
Student with two private fields: Name name and CourseCollection course.
Name with two fields String firstName and String surname.
CourseCollection with ArrayList courses.
(Info: Later, I will work with class UserDatabase to collect and load a collection of students,
+ class DatavaseFormatException which will represent errors, but I think it would be easier to finish those 3 classes above first? Correct me if
I'm wrong.)
QUESTION:I need a little help with class Name, I don't think my work is correct.
My main issue is with the method String encode, and constructor Name(String encodedIdentity)
where I want to return the names, split by a ;. Here's what I have
enter code here
public class Name
//instanciating the persons first and last name as Strings.
private String firstName;
private String surname;
/**
* Constructor for objects of class Name- setting the text values for a name
*/
public Name(String firstName, String surname)
{
firstName = this.firstName;
surname = this.surname;
}
/**
* Constructor for objects of class Name- reconstructing the fields
* from a coded name
*/
public Name(String encodedIdentity)
{
//Here, the name is supposed to be coded as a text value, with the first
//and last names split with a ;
this.encodedIdentity=encodedIdentity;
//I am getting my first error here
}
//getters for firstname and surname here
/**
* This method will return the name, with the first and last name split
* by a ;
*/
public String encode()
{
//Could I use a split String here? If so how?
return firstName + ";" + surname;
}
}
I can guarantee I will need further help with my work. Thanks in advance, I find
people on StackOverflow to be very helpful as I don't have anyone (other than my books)
to ask for help. (I know you guys are not free teachers. But if anyone would voulenteer to help me outside of this I would highly appreciate it.
(Sorry if that's not allowed to ask for!))
EDIT: Thanks to you guys, my class is now compiling. I am not sure how to test it yet, but this is what I have now. Does it look correct?
public class Name
{
/**
* Constructor for objects of class Name- setting the text values for a name
*/
public Name(String firstName, String surname)
{
this.firstName = firstName;
this.surname = surname;
}
/**
* Constructor for objects of class Name- reconstructing the fields
* from a coded name
*/
public Name(String encodedIdentity)
{
String names = firstName + surname;
String[] fullname = names.split( "\\;");
if(fullname.length != 2 )
{
System.out.println(fullname);
}
}
/**
* Getting the firstname of the person
* #return firstName
*/
public String getFirstName()
{
return firstName;
}
/**
* Getting the surname of the person
* #return surname
*/
public String getSurname()
{
return surname;
}
/**
* This method will return the name, with the first and last name split
* by a ;
*/
public String encode()
{
String encode = (firstName + ";" + surname);
return encode;
}
}
If you are given an "encoded id", split it to get the names:
public Name(String encodedIdentity){
String[] names = split( ";", encodedIdentity );
if( names.length != 2 ) throw new IllegalArgumentError("...");
firstName = names[0];
surname = names[1];
}
One does not store all the variants with which an object's attributes may be specified. Therefore, there shouldn't be a field encodedIdentity.
First correct your name constructor with two fields
replace this
public Name(String firstName, String surname)
{
firstName = this.firstName;
surname = this.surname;
}
with
public Name(String firstName, String surname)
{
this.firstName = firstName;
this.surname = surname;
}
Also, can you paste the error from console here. so that it will be easier to find the exact problem.

Constructor is Undefined issues

I'm currently writing a program that should read through a text file, create an array of different types of employees (each have their own subclass), then print out the information in a different format. I think I've got most of it working, but whenever I try to actually create the objects (at least I think that's what it is?), I'm getting a "Constructor is undefined" error. This is happening on all 7 of these objects. I will simply post one here (along with its subclass) so that you guys aren't overloaded with information, and hopefully I can figure out the rest from that.
Thanks for any help you can provide!
Driver class where I'm reading and creating objects (did not include the rest of the code following this)
Error occurs at the "Emp[0]" line
import java.io.File;
import java.util.Scanner;
public class PayrollSystemTest2 {
/**
* #param args
*/
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
Scanner input;
input = new Scanner(new File("EmployeePayrollInfo.txt"));
Employee[] Emp = new Employee[20];
while(input.hasNext())
{
String ID = input.nextLine();
if (ID.charAt(0) == 'S')
{
String first = input.nextLine();
String last = input.nextLine();
String ssn = input.nextLine();
Date DayOfBirth = new Date(input.nextInt(),input.nextInt(),input.nextInt());
double salary = input.nextDouble();
Emp[0] = new SalariedEmployee(first, last, ssn, DayOfBirth, ID);
}
SalariedEmployee subclass
public class SalariedEmployee extends Employee
{
private double weeklySalary;
// four-argument constructor
public SalariedEmployee( String first, String last, String ssn, Date DayOfBirth, String ID,
double salary )
{
super( first, last, ssn, DayOfBirth, ID); // pass to Employee constructor
setWeeklySalary( salary ); // validate and store salary
} // end four-argument SalariedEmployee constructor
// set salary
public void setWeeklySalary( double salary )
{
double baseSalary;
if ( salary >= 0.0 )
baseSalary = salary;
else
throw new IllegalArgumentException(
"Weekly salary must be >= 0.0" );
} // end method setWeeklySalary
// return salary
public double getWeeklySalary()
{
return weeklySalary;
} // end method getWeeklySalary
// calculate earnings; override abstract method earnings in Employee
#Override
public double earnings()
{
return getWeeklySalary();
} // end method earnings
// return String representation of SalariedEmployee object
#Override
public String toString()
{
return String.format( "salaried employee: %s\n%s: $%,.2f",
super.toString(), "weekly salary", getWeeklySalary() );
} // end method toString
} // end class SalariedEmployee
Again, thanks for any help you can provide.
Well yes - look at your constructor, including the clearly-inaccurate comment:
// four-argument constructor
public SalariedEmployee(String first, String last, String ssn, Date DayOfBirth,
String ID, double salary)
Note how there are 6 parameters. Now here's how you're trying to call it:
Emp[0] = new SalariedEmployee(first, last, ssn, DayOfBirth, ID);
You're passing in 5 arguments. What happened to the salary?
As side notes:
Java variables are conventionally camelCased - so dayOfBirth and id rather than DayOfBirth and ID
Using double for financial values such as a salary is a bad idea. Use BigDecimal or keep an integer number of cents. (That's assuming you even need it down to the cent...)

Creating objects from data entered by user

I'm working on a homework project that requires me to create an object from data entered by a user. I have a class called Person which takes the basic information, a class called Customer which extends the Person class and includes a customer number and a class called Employee which extends the Person class and returns a social security number.
I have pasted the code from my main program below. I'm a little confused on a couple of things. First when I'm collecting the information (first name, last name etc) amd I supposed to be accessing my Person class in there somehow?
Second I guess more plainly, how do I create the object? so far in all of the examples I have read online I find they seem to enter the information already like if I were to have it say
Person firstName = new Person(Jack);
Although I am collecting the information from the user so I don't see how to tell it like
Person firstName = new Person (enter info from user here);
Finally and again this is a really dumb question but I have to create a static method that accepts a Person object.
To create the static method I'm assuming it is
Public Static print()
but how do I tell it to print something from the person class? how does it know?
Most of my examples in the book include a class that contains all of the information instead of making the user enter it which is confusing because now I'm being told the user has the freedom to type what they want and I need to collect that information.
import java.util.Scanner;
public class PersonApp
{
public static void main(String[] args)
{
//welcome user to person tester
System.out.println("Welcome to the Person Tester Application");
System.out.println();
Scanner in = new Scanner(System.in);
//set choice to y
String choice = "y";
while (choice.equalsIgnoreCase("y"))
{
//prompt user to enter customer or employee
System.out.println("Create customer or employee (c/e): ");
String input = in.nextLine();
if (input.equalsIgnoreCase("c"))
{
String firstName = Validator.getString(in, "Enter first name: ");
String lastName = Validator.getString(in, "Enter last name: ");
String email = Validator.getEmail(in, "Enter email address: ");
String custNumber = Validator.getString(in, "Customer number: ");
}
else if(input.equalsIgnoreCase("e"))
{
String firstName = Validator.getString(in, "Enter first name: ");
String lastName = Validator.getString(in, "Enter last name: ");
String email = Validator.getEmail(in, "Enter email address: ");
int empSoc = Validator.getInt(in, "Social security number: ");
}
}
System.out.println("Continue? y/n: ");
choice = in.next();
}
}
First, I observe that there isn't a Person object. I assume you'll get around to creating that, so I'm not going to concern myself too much with it.
Insofar as actually getting the data, you're halfway there. Depending on how you want to frame the Person object, you can create a new Customer or Employee object by passing the values which you received from the user.
Customer customer = new Customer(firstName, lastName, email, custNumber);
or
Employee employee = new Employee(firstName, lastName, email, empSoc);
Here's the snippet of both:
public class Person {
public Person (String first, String last, String email) {
// You'd fill in code here for handling the variables
}
// ...
}
public class Customer extends Person {
public Customer (String first, String last, String email, String custNo) {
super(first, last, email);
// You'd fill in code here for handling the variables
}
// ...
}
public class Employee extends Person {
public Employee (int social) {
super(first, last, email);
// You'd fill in code here for handling the variables
}
// ...
}
To print something from the Person class, using that static method (why? You could override toString() instead), you frame it such that your Person object has accessors to each of the fields relevant to a Person. This would mean you have a getFirstName(), getLastName(), and so forth, relevant to the object if it's an employee or a customer. (I leave that as an exercise to you.)
In that sense, one would then only require calls to those accessors to print the value.
public static void print(Person p) {
System.out.println(p.getFirstName()) + " " + p.getLastName()); // You can get the trend from here.
}
To print the Person object you can just use the System.out.println() if you just want to print it to the command line, but you'll get some unreadable nonsense.
What the println() method does is, if the object is not a String call it's toString() method, because all objects have one, it is defined in java.lang.Object. But that method gives us unreadable things mentioned above, so you have to override it to do something like
public class Person
{
String firstName;
String Lastname;
public Person(String firstName, String lastName)
{
this.firstName = firstName;
this.lastName = lastName;
}
public String toString()
{
// Create a String that represents this object
return "This person is called " + firstName + " " + lastName;
}
}
To create an object you can read the Strings from the commandline and then pass them into the constructor as Makoto suggests.

I have a method and I want to return three different values to my main method

Lets say I have this program below. Now I want to pass both the users first name AND last name into the method without calling it again and changing the parameter and making the user retype there first name and last name again.
I know I can make two different methods for finding the first name and last name but I was wondering if there was a way to do this is just one method.
import java.util.Scanner;
public class Document3 {
public static void main(String[] args) {
String name;
name = getName("lastName"); //But how would I get my lastName WITHOUT recalling the method with "lastName" in the parameters?
System.out.println(name); //I want to also get the other name into in my main method somehow
}
public static String getName(String nameOption) {
Scanner x = new Scanner(System.in);
String firstName = "";
String lastName = "";
String nameChoice = "";
System.out.print("Please enter your first name: ");
firstName = x.nextLine();
System.out.print("\nPlease enter your last name: ");
lastName = x.nextLine();
if (nameOption.equals("firstName")) {
nameChoice = firstName;
}
if (nameOption.equals("lastName")) {
nameChoice = lastName;
}
return nameChoice; //how do I return both variables (firtName and lastName) and how would I access them
}
}
Create a small wrapper class which holds the values you want to return, and return an instance of that class.
class Name
{
final String firstName;
final String lastName;
Name(String first, String last)
{
firstName = first;
lastName = last;
}
}
How to use it:
public static void main(String[] args)
{
Name name = getName();
String first = name.firstName;
String last = name.lastName;
}
public static Name getName()
{
Scanner x = new Scanner(System.in);
System.out.print("Please enter your first name: ");
String firstName = x.nextLine();
System.out.print("\nPlease enter your last name: ");
String lastName = x.nextLine();
return new Name(firstName, lastName);
}
You can create another class called Fullname which contains two attribute , first name and last name. Then inside your getName function, return the Fullname object.
Yes, return an object, a map, or an array (ew). Java doesn't have a way to return multiple values without wrapping them up into a single object.

Categories

Resources