Java Help: Using Classes - java

Now I have read and on this but i am just stuck. Any help appreciated. I am looking for hints. The code compiles and runs fine but I don't think the variables are being stored in the employee class and I am not sure I am understanding my use of the constructor right.
Requirements:
I have completed:
Values are checked to ensure they are
positive numbers.
Entering stop as the
employee name end program.
Having trouble on
Uses a class to store
name
hourly rate
hours worked
Use a constructor to initialize the employee information
and a method within that class to
calculate the weekly pay.

Here are a couple hints:
Use a constructor to initialize the
employee information
Looking at the provided code, there is a single constructor which takes no arguments and will initialize the fields of the object to zero.
Perhaps the "constructor to initialize the employee information" means that the constructor should be able to accept values which the Employee object should initlialize its fields to.
The Java Tutorials has a page on Providing Constructors for Your Classes with examples which should help in creating such constructor.
... and a method within that class to
calculate the weekly pay
This seems to say that there should be a method that is only visible to itself and not available from others in order to calculate the value for the weeklyPay field.
Again, from The Java Tutorials, Controlling Access to Members of a Class discusses show to change the visibility of methods.
Reading the contents of the assignment, it seems like taking a look at the Lesson: Classes and Objects of The Java Tutorials may be of use, as it provides some good examples and explanations on the concepts of object-oriented programming.

In addition to the fact that you haven't used the constructor to set your variables, as mentioned by others. The setter methods are performing no-ops. Which is why you aren't getting the results you expect. You are setting the local var to itself and not to the member var.
You need to either change your local var names, change the member var names, or change the setters to use the 'this' keyword
public void sethoursWorked(float hoursWorked)
{
this.hoursWorked = hoursWorked;
}

You'll notice that you are asked to make a class that stores the name, the hourly rate, and the hours worked, while you are asked to make a method that calculates the weekly pay. In other words, you should not have a weeklyPay instance variable. Whenever the user asks for the weekly pay (by means of your getWeeklyPay() method), you calculate and return it directly, without storing it in an instance variable.
Then, in order to actually use that result, you'll need to change this:
Employee.getweeklyPay();// Calculate weeklyPay ( hoursWorked * hourlyRate )
weeklyPay = ( hoursWorked * hourlyRate );
into something like this:
weeklyPay = employee.getWeeklyPay();
If you don't actually assign the result of your method to some variable, you can't use the result.

The final answer from the OP:
/** Payroll3.java | Due 8/09/09
** IT 2015 Java Programming | lazfsh | Axia College - University of Phoenix */
import java.util.Scanner;// Import and use scanner
public class Payroll3 {// main method begins
public static void main( String args[] ) {
// Initialize
boolean stop = false;// Variable for exit procedure
String endProgram = "";// Variable to explain exit procedures blank 1st time
int version = 3;// Version number
// Welcome message
System.out.printf(
"\nWelcome to the Payroll Program v.%d\n", version );//Welcome message
while ( stop == false) {// Run program until stop equals true
Scanner input = new Scanner( System.in );// new Scanner for CL input
Employee Employee = new Employee(); // new Employee constructor
// Prompt for and input name
System.out.printf( "\nEnter name of the employee%s:", endProgram );
Employee.setempName(input.nextLine());// Accept input & Store
if ( Employee.getempName().equals( "stop" )) {// If = end program w/message
System.out.printf( "\n%s\n%s\n\n", "....", "Thanks for using Payroll Program");
stop = true;}
else{// Continue retrieve hourlyRate, hoursWorked & Calculate
do {// Prompt for and input hourlyRate
System.out.printf( "\n%s", "Enter hourly rate: $" );
Employee.sethourlyRate(input.nextFloat());// Accept input & Store
if ( Employee.gethourlyRate() < 1 ) {// Show error for negative #
System.out.printf( "%s", "Enter a positive number.");}
else;{}// Continue
} while ( Employee.gethourlyRate() < 1 );// End loop if positive number recieved
do {// Prompt for and input hoursWorked
System.out.printf( "\n%s", "Enter number of hours worked:" );
Employee.sethoursWorked(input.nextFloat());// Accept input & Store
if ( Employee.gethoursWorked() < 1 ) {// Show error for negative #
System.out.printf( "%s", "Enter a positive number.");}
else;{}// Continue
} while ( Employee.gethoursWorked() < 1 );// End loop if positive number recieved
// Display formatted results
System.out.printf( "\n%s's weekly pay is $%,.2f\nHourly rate ($%,.2f) multiplied by hours worked (%.0f)\n\n...Ready for next employee.\n\n",
Employee.getempName(), Employee.getweeklyPay(), Employee.gethourlyRate(), Employee.gethoursWorked() );
// Debug Line Employee.showVariables();
}// end retrieve hourlyRate, hoursWorked & Calculate
endProgram = ( ", \n(Or type \"stop\" to end the program)" );//explain exit procedure on second empName prompt
}// ends program when stop equals true
}// end method main
}//end class Payroll3
Employee class
/** Employee Class | Initializes and storeds data for employee
Also provides method to calculate weekly pay.
*/
// Import statements
import java.util.Scanner;// Import and use scanner
public class Employee {//Begin Employee class
Scanner input = new Scanner( System.in );// new Scanner for CL input
// Declare instance variables
String empName; // Declare name as string
float hourlyRate; // Declare hourlyRate as float
float hoursWorked; // Declare hoursWorked as float
// constructor initializes employee information
public Employee() { // Initialize (clear) instance variables here
empName = "";
hourlyRate = 0;
hoursWorked = 0;
} // end constructor
// Begin methods
public void setempName(String empName) {// public method to set the employee name
this.empName = empName;}// end method setempName
public String getempName() {// public method to get the employee name
return empName;}// end method getempName
public void sethourlyRate(float hourlyRate) {// public method to set the hourly Rate
this.hourlyRate = hourlyRate;}// end method set hourly Rate
public float gethourlyRate() {// public method to retrieve the hourly Rate
return hourlyRate;} // end method get hourly Rate
public void sethoursWorked(float hoursWorked) {// public method to set the hours Worked
this.hoursWorked = hoursWorked;} // end method set hours Worked
public float gethoursWorked() {// public method to retrieve the hours Worked
return hoursWorked;} // end method get hours Worked
public float getweeklyPay() {// public method to retrieve weekly Pay
return ( hoursWorked * hourlyRate );}// end method get weeklyPay
/* Test line
public void showVariables(){
System.out.printf( "empName=%s, hourlyRate=%s, hoursWorked=%s", this.empName, this.hourlyRate, this.hoursWorked );} */
} // end class Employee

Related

Questions about creating UML Class diagram from Java program - default constructor? Are there no attributes in this example?

I have a class where I have to manually create a UML diagram for the program below. In order to understand better, I automatically created a UML diagram in Eclipse with ObjectAid.
I have a few questions I would like to understand:
Of the three sections class, attributes, and methods, why is "PayrollDialog()" included in the methods section? Is it because you should always include the default constructor?
Are JOptionPane.showInputDialog really not considered for the methods section? Why not? I ask because I notice getting the user name, hours worked, and pay rate are not included.
Are there really no attributes to be listed in the UML for this program? I think this is correct because they are not listed under the public class PayrollDialog.
Is the UML diagram listed really accurate for this program? If not, what should it look like? I find it hard to believe the assignment is that simple.
import javax.swing.JOptionPane;
/**
4 * This program demonstrates using dialogs
* with JOptionPane.
*/
public class PayrollDialog
{
public static void main(String[] args)
{
String inputString; // For reading input
String name; // The user's name
int hours; // The number of hours worked
double payRate; // The user's hourly pay rate
double grossPay; // The user's gross pay
// Get the user's name.
name = JOptionPane.showInputDialog("What is " +
"your name? ");
// Get the hours worked.
inputString =
JOptionPane.showInputDialog("How many hours " +
"did you work this week? ");
// Convert the input to an int.
hours = Integer.parseInt(inputString);
// Get the hourly pay rate.
inputString =
JOptionPane.showInputDialog("What is your " +
"hourly pay rate? ");
// Convert the input to a double.
payRate = Double.parseDouble(inputString);
// Calculate the gross pay.
grossPay = hours * payRate;
// Display the results.
JOptionPane.showMessageDialog(null, "Hello " +
name + ". Your gross pay is $" +
grossPay);
// End the program.
System.exit(0);
}
}
Yes you are basically correct.
JOptionPane is not listed in the Class Diagram because it is found in javax.swing.JOptionPane and its not globally declared as property/attribute or method of your PayrollDialog class.
Based on your source code, there are no global properties/attribute declared.
For example
class PayrollDialog{
static JFrame f; // this would appear as property in UML
public static void main(String[] args){..}
}

Error: variable might not have been initialised in my CellPhoneBill program

I am getting these 3 errors after compiling .. Pls help and thnx in advance..
error: variable ac might not have been initialized
tcws= cm+tm+ac+am+ta;
error: variable am might not have been initialized
tcws= cm+tm+ac+am+ta;
error: variable ta might not have been initialized
tcws= cm+tm+ac+am+ta;
My code:
import java.lang.*;
import java.util.Scanner;
class CellPhoneBill {
public static void main(String[]args) {
double cm ,tm ,ac, am, ta, tcws, tax, taxpluscost ;
Scanner s=new Scanner(System.in);
System.out.print("Enter the number of minutes and also enter the number of text messages ");
cm= s.nextDouble();
tm= s.nextDouble();
if(cm<=50&& tm<=50) {
System.out.print("Base charge= $15.00"); }
else if(cm>50 && tm>50) {
System.out.println("Enter no of additional call minutes (if any) and additional messages(if any) ");
ac=s.nextDouble();
am= s.nextDouble();
cm=0.25* ac;
am=0.15*am;
System.out.println("Additional call charges = " +ac);
System.out.println("Additional message charges = " +am);
ta=ac+am;
System.out.println("Total Additional charges = " +ta);
}
else if(cm>=0&& tm>=0) { System.out.println("911 Call charges =$0.44" );
}
else {
tcws= cm+tm+ac+am+ta;
System.out.println("Total cost without Sales Tax ="+tcws);
tax=( 5/100.00*(tcws));
System.out.println(" 5% Sales Tax ="+tax);
taxpluscost=tcws+tax;
System.out.println("Total cost Including 5% Sales Tax ="+taxpluscost);
}
}
}
It means that the variables ac, am and ta have not been assigned any value. You cannot sum variables that haven’t got any value.
For the fix, it depends on what you are trying to obtain. Maybe you need to do ac=s.nextDouble(); as in some of the other cases to read a value from the user. Or maybe you just need to do ac = 1.0; or whatever the appropriate value would be. And the same for the other two variables, of course.
Possibly you intended a different if-else structure where the values assigned to the three variables in one if branch should also be used in the last else part?
For Auto initialization you can declare them in your class as instance variable instead in static method.You can use the same variable in your static method then.
Your scanner only prompts the user for two values initially, neither of which are ac or am. Thusac = s.nextDouble() and am = s.nextDouble () aren't actually assigning values to ac and am
In java references to primitive data types are stored in the same register as the variable.
double a = 12.345;
Initializes a variable a and sets it to the value of 12.345.
You must initialize your variables prior to using them lest you get an error.
edited for corrections

Amortization Table

This program will calculate the amortization table for a user. The problem is my assignment requires use of subroutines. I totally forgot about that, any ideas on how to modify this to include subroutines?
public class Summ {
public static void main(String args[]){
double loanamount, monthlypay, annualinterest, monthlyinterest, loanlength; //initialize variables
Scanner stdin = new Scanner (System.in); //create scanner
System.out.println("Please enter your loan amount.");
loanamount = stdin.nextDouble(); // Stores the total loan amount to be payed off
System.out.println("Please enter your monthly payments towards the loan.");
monthlypay = stdin.nextDouble(); //Stores the amount the user pays towards the loan each month
System.out.println("Please enter your annual interest.");
annualinterest = stdin.nextDouble(); //Stores the annual interest
System.out.println("please enter the length of the loan, in months.");
loanlength = stdin.nextDouble(); //Stores the length of the loan in months
monthlyinterest = annualinterest/1200; //Calculates the monthly interest
System.out.println("Payment Number\t\tInterest\t\tPrincipal\t\tEnding Balance"); //Creates the header
double interest, principal; //initialize variables
int i;
/* for loop prints out the interest, principal, and ending
* balance for each month. Works by calculating each,
* printing out that month, then calculating the next month,
* and so on.
*/
for (i = 1; i <= loanlength; i++) {
interest = monthlyinterest * loanamount;
principal = monthlypay - interest;
loanamount = loanamount - principal;
System.out.println(i + "\t\t" + interest
+ "\t\t" + "$" + principal + "\t\t" + "$" + loanamount);
}
}
}
any ideas on how to modify this to include subroutines?
Well, you are better off doing it the other way around; i.e. working out what the methods need to be before you write the code.
What you are doing is a form or code refactoring. Here's an informal recipe for doing it.
Examine code to find a sections that perform a specific task and produces a single result. If you can think of a simple name that reflects what the task does, that it a good sign. If the task has few dependencies on the local variables where it currently "sits" that is also a good sign.
Write a method declaration with arguments to pass in the variable values, and a result type to return the result.
Copy the existing statements that do the task into the method.
Adjust the new method body so that references to local variables from the old context are replaced with references to the corresponding arguments.
Deal with the returned value.
Rewrite the original statements as a call to your new method.
Repeat.
An IDE like Eclipse can take care of much of the manual work of refactoring.
However, the real skill is in deciding the best way to separate a "lump" of code into discrete tasks; i.e. a way that will make sense to someone who has to read / understand your code. That comes with experience. And an IDE can't make those decisions for you.
(And did I say that it is easier to design / implement the methods from the start?)
I deleted my previous comment as I answered my own question by reading the associated tags :-)
As an example, define a method like this in your class:
public double CalculateInterest(double loanAmount, double interestRate) {
//do the calculation here ...
}
And then call the method by name elsewhere in your class code e.g.
double amount = CalculateInterest(5500, 4.7);

Looping through Arrays in Java

I am trying to write a program to simulate an airline reservation system. I an supposed to use an array of type boolean to represent the number of seats. First five seats represent first class and last five represent economy. Initially the program must allow the user to make a choice between first class and economy and then his choice is processed as follows:
A user can only be assigned an empty seat in the class he chooses.
Once a class is full, the user is offered the option to move to the next class
If the user agrees to move to the next class a simple boarding pass is printed.
If the user refuses to move to the next class. The time for the next flight is displayed. i would appreciate help on how to loop through the elements of the array to determine whether its true of false. Also i am trying to display the number of seats available in each class before the user makes a selection this is what i've written so far.. My code is far from complete, i acknowledge that, i am a novice programmer please help. Thank you.
import java.util.Scanner;
public class AirlineReservation
{
private boolean[] seats =; // array to hold seating capacity
private String AirlineName; // name of airline
private int[] counter = new int[5]
// constructor to initialize name and seats
public Airline(String name, boolean[] capacity )
{
AirlineName = name;
seats = capacity;
} // end constructor
// method to set the Airline name
public void setName( String name )
{
AirlineName = name; // store the course name
} // end method setCourseName
// method to retreive the course name
public String getName()
{
return AirlineName;
} // end method getName
// display a welcome message to the Airline user
public void displayMessage()
{
// display welcome message to the user
System.out.printf("Welcome to the Self-Service menu for\n%s!\n\n",
getName() );
} // end method displayMessage
// processUserRequest
public void processUserRequest()
{
// output welcome message
displayMessage();
// call methods statusA and StatusB
System.out.printf("\n%s %d:\n%s %d:\n\n",
"Number of available seats in First class category is:", statusA(),
"Number of available seats in Economy is", statusB() );
// call method choice
choice();
// call method determine availability
availability();
// call method boarding pass
boardingPass();
} // end method processUserRequest
public int statusA()
{
for ( int counter = 0; counter <= (seats.length)/2; counter++ )
} // revisit method
// method to ask users choice
public String choice()
{
System.out.printf(" Enter 0 to select First Class or 1 to select Economy:")
Scanner input = new Scanner( System.in );
boolean choice = input.nextBoolean();
} // end method choice
// method to check availability of user request
public String availability()
{
if ( input == 0)
System.out.printf("You have been assigned seat number \t%d", seats[ counter ]);
else
System.out.printf("You have been assigned seat number \t%d", seats[ counter ]);
}
}
#Anthony : As you are novice, hence please look at following comments :
1. Be specific while asking your question. In this case the question was "how to loop through array!". You posted complete problem statement.
2. Please google it or research it properly on internet if similar question has been asked by anybody before. In this case, similar question can be find here :
Iterate through string array in Java
Because of these reasons people are giving your query downvote!
Now just want to provide answer to your question as you look quite new to programming :
boolean flag[] = {true,false,true,false};
for(int i=0;i<flag.length;i++){
System.out.println(flag[i]);
}
I hope it helps!

need to figure out how to manipulate the mutator to figure out a class according to professor, I am confusd on how to do that

I know we aren't suppose to post homework problems but I am having issues I have talked with him and after 45 minutes I am more confused then I was before he said that this was suppose to be confusing.
So we are working on making our own classes and one of them was making a class to later be used in a weight converter on other planets (mainly the Moon, Mercury, Venus, Jupiter and Saturn) I have managed to make the class (code below)
/*
* WeightConverter class
* Class Description - A Java class for converting weight on different plants
* Author: J. Wilson
* Date: 2/24/2015
* Filename: WeightConverter.java
*/
// class beginning
class WeightConverter {
//create the variable that stores the conversion rate
private double weightchange;
//the constructor
public WeightConverter(double weight){
weightchange=weight;
}
//accessor
public double smallstep(){
return weightchange;
}
//mutator for the needed variable
public void setweightratio(double number){
weightchange=number;
}
//and the method convert.
public double convert(double planet){
return planet*weightchange;
}
}
//end of class
but he added the stipulation that "In this WeightCalculator class, I expect you to use each method you created at least once.or lose a point for each one your don't use " I asked him how I go about it and after a 45 minute talk i'm more confused then before after he mentioned I can take my mutator and just manipulate that here is what I have currently and it works so far
/*
* WeightConverter on other planets
* Program Description - weightchanger
* Author: J.Wilson
* Date: 2/24/2015
* Filename: WeightCalculator.java
*/
//import statements
import java.util.*; //example
// class beginning
class WeightCalculator {
public static void main(String[] args ) {
//Declare variables area
WeightConverter test;
Scanner scan = new Scanner ( System.in );//reads what is entered into the keyboard by the user
double pounds;
//Program beginning messages to user here
System.out.println("Hello! Welcome to my weight converter program");
System.out.println();//blank space
System.out.println("Please enter your weight (in pounds): ");
pounds=scan.nextDouble();
WeightConverter moon = new WeightConverter(.167);
System.out.println("Your weight on the moon is " + moon.convert(pounds));
//Collect inputs from user or read in data here
//Echo input values back to user here
//Main calculations and code to
//Output results here
//End program message
System.out.println();
System.out.println("Hope you enjoyed using this program!");
}// end main method
}// end class
can anyone explain by what he means by using my mutator more than once? or in laymans terms how to go about doing it?
It sounds like you should be using setWeightRatio() each time you want to get the weight on a new planet.
You first created the moon object and set its weight and then later used that set weight in moon.convert()
Next you should setWeightRatio() to a different amount (for Jupiter or Venus or whatever) and that will set the weightChange variable to the new double you just passed in. Then when you use convert() it will access the new weightChange variable and compute based on that.
I would create a single planet object and then reset its weightChange variable through the mutator as necessary. Then use convert() between setting new weight ratio.
You professor said that you have to use all the methods in your class at least once, correct?
your setweightratio method is useless (this should be obvious, as you havent used it !). it sets the class variable weightchange to its input argument, but the same thing happens in the constructor, so you would not need to call it again.
You have two options:
You've already returned moon weight to the user. When the next planet is in question, keep your WeightConverter instance and call moon.setweightratio(ratio of Venus or whatever). Using moon.convert(pounds) will then use the new ratio.
Alternatively, remove the setweightratio method all together (so you don't get points off for not using it) and create WeightConverter objects for each planet. This is less elegant.

Categories