Finding the highest and the lowest value - java

I have this assignment I gotta do. It looks good, except for the getHighest output and the getLowest result. Here's my code:
KNW_CourseGradesV2 Class:
public class KNW_CourseGradesV2 implements KNW_Analyzable
{
//Declare array variable
private KNW_GradedActivity[] grades = new KNW_GradedActivity[4];
String results;
/**
* Constructor
* */
public KNW_CourseGradesV2()
{
}
public void setLab(KNW_GradedActivity lab)
{
grades[0] = lab;
}
public void setPassFailExam(KNW_GradedActivity pfe)
{
grades[1] = pfe;
}
public void setEssay(KNW_GradedActivity essay)
{
grades[2] = essay;
}
public void setFinalExam(KNW_FinalExam fe)
{
grades[3] = fe;
}
public void setTotalGrade(KNW_GradedActivity tg)
{
grades[4] = tg;
}
public String toString()
{
//Lay out all of the scores
return "Lab Score: " + grades[0].getScore() +
"\tGrade: " + grades[0].getGrade() +
"\nPass/Fail Exam: " + grades[1].getScore() +
"\tGrade: " + grades[1].getGrade() +
"\nEssay Score: " + grades[2].getScore() +
"\tGrade: " + grades[2].getGrade() +
"\nFinal Exam Score: " + grades[3].getScore() +
"\tGrade: " + grades[3].getGrade();
}
//Find the average of the grades
public double getAverage()
{
double sum = 0.0;
double average = 0.0;
double total = 0.0;
//For loop to calc. the average
for(int i =0; i<grades.length; i++)
{
total =+ grades[i].getScore();
average = sum/grades.length;
}
return average;
}
public KNW_GradedActivity getHighest()
{
double highest = grades[0].getScore();
for(int i = 0; i < grades.length; i++)
{
if(grades[i].getScore() > highest)
{
highest = grades[i].getScore();
}
}
//Created KNW_GradedActivity object to bring the highest number
//into the setScore method so it can be a double
KNW_GradedActivity gaH = new KNW_GradedActivity();
gaH.setScore(highest);
return gaH;
}
public KNW_GradedActivity getLowest()
{
double lowest = grades[0].getScore();
for(int i = 0; i < grades.length; i++)
{
if(grades[i].getScore() > lowest)
{
lowest = grades[i].getScore();
}
}
//Samething here, just doing it for the lowest number
KNW_GradedActivity gaL = new KNW_GradedActivity();
gaL.setScore(lowest);
return gaL;
}
}
KNW_Analyzable Class:
public interface KNW_Analyzable
{
double getAverage();
KNW_GradedActivity getHighest();
KNW_GradedActivity getLowest();
}
KNW_GradedActivity Class:
public class KNW_GradedActivity
{
private double score; // Numeric score
/**
The setScore method sets the score field.
#param s The value to store in score.
*/
public void setScore(double s)
{
score = s;
}
/**
The getScore method returns the score.
#return The value stored in the score field.
*/
public double getScore()
{
return score;
}
/**
The getGrade method returns a letter grade
determined from the score field.
#return The letter grade.
*/
public char getGrade()
{
char letterGrade;
if (score >= 90)
letterGrade = 'A';
else if (score >= 80)
letterGrade = 'B';
else if (score >= 70)
letterGrade = 'C';
else if (score >= 60)
letterGrade = 'D';
else
letterGrade = 'F';
return letterGrade;
}
}
And here is the output I get. I will just show the problem I am facing, won't show all of the output.
Output:
Average: 0.0
Highest: KNW_GradedActivity#565d3fa7
Lowest: KNW_GradedActivity#655c4395>
I have been trying for about a week to figure this out and find what is happening, and I can't seem to find it.

Notice that in the return of your methods, you are actually returning gaH and gaL, both of which are KNW_GradedActivity Objects. If you want to see the score, you should probably return gaH.getScore() and gaL.getScore().

Why not to use Stream and DoubleSummaryStatistics to get the stats? Let the api do all the calculations:
List<KNW_GradedActivity> grades = Arrays.asList(new KNW_GradedActivity(), new KNW_GradedActivity(), new KNW_GradedActivity());
grades.get(0).setScore(91);
grades.get(1).setScore(81);
grades.get(2).setScore(71);
DoubleSummaryStatistics statistics = grades.stream().
collect(Collectors.summarizingDouble(KNW_GradedActivity::getScore));
System.out.println(statistics);
// DoubleSummaryStatistics{count=3, sum=243.000000, min=71.000000, average=81.000000, max=91.000000}

Another alternative is to override toString method in your KNW_GradedActivity class:
#Override
public String toString() {
return "{" +
"score=" + score +
", grade='" + getGrade() + '\'' +
'}';
}
This way you dont have to change your actual print statement and will have a nice output combining your score and grade. It will look like:
{score=90.0, grade='A'}

Related

Maximum and minimum method java

This program is supposed to find the maximum, minimum, and average of grades. User inputs int inputGrade and the program displays letter it is. It's supposed to do this how however many students are needed. I'm having trouble writing the method where it finds the max and min. (yes I've talked to my teacher if anyone's wondering...) I pasted the methods below (they don't work). Just like IN GENERAL, does anyone know how to find the maximum and minimum of a set of entered numbers? (not using arrays, lists, or any unusual imports other than scanner) ** note I've updated this a lot...
import java.util.Scanner;
public class GetLetterGrade
{
static int inputGrade; // input grade
public static void main(String [] args)
{
Scanner reader = new Scanner(System.in);
int classAverage;
int classMin; // class's minimum grade
int classMax; // class's maximum grade
while (inputGrade != -1) // while user is entering grades
{
System.out.println("Welcome to the grade calculator. \nPlease enter a
numeric grade. After the last student in the class, enter a grade of
-1.");
inputGrade = reader.nextInt();
letterGrade(inputGrade); // calls letter grade method
findMaxAndMin();
result();
}
}
// find letter grade
public static String letterGrade(int numGrade)
{
String gradeMessage = "";
{
if (numGrade >= 96 && numGrade <= 100) // if numeric grade is 96-100 then
it's A+
{
gradeMessage = "That's an A+.";
result();
// DOES THIS FOR GRADES A+ TO F, NOT SHOWN, too much to paste!
}
}
}
return gradeMessage;
}
public static int findCharGrade(int numGrade)
{
char letter;
if (numGrade >= 90 && numGrade <= 100) // A
{
letter = 'A';
}
else if (numGrade >= 80 && numGrade < 90) // B
{
letter = 'B';
}
else if (numGrade >= 70 && numGrade < 80) // C
{
letter = 'C';
}
else if (numGrade >= 60 && numGrade < 70) // D
{
letter = 'D';
}
else if (numGrade < 60) // F
{
letter = 'F';
}
}
// finds maximum and minimum grades
public static int findMaxAndMin(int inputGrade)
{
int max = Math.max(inputGrade, max);
int min = Math.min(inputGrade, min);
if (inputGrade < max)
{
inputGrade = max;
findCharGrade(inputGrade);
}
else if (inputGrade > min)
{
inputGrade = min;
findCharGrade(inputGrade);
}
}
public static void calcAverage(int sumOfGrades, int numOfStudents)
{
// something goes here
}
// finds results
public static void result()
{
int min = findMaxAndMin(inputGrade);
int max = findMaxAndMin(inputGrade);
System.out.println("Please enter a numeric grade");
int inputGrade = reader.nextInt();
letterGrade(inputGrade);
if (inputGrade == -1)
{
System.out.println("You entered " + numOfStudents + " students. Class
Average: " + average + " Class Minimum: " + min + " Class maximum: " + max
+ " \nThanks for using the class grade calculator!");
}
}
here is a more simplistic way of doing it not using Lists or arrays
double sum = 0; // use double so that you do not do integer arithmetic
int count = 0;
int min = Integer.MAX_VALUE; // set to very high value
int max = Integer.MIN_VALUE; // set to bery low value
Scanner scan1 = new Scanner(System.in);
System.out.println("enter numbers (-1 to quit");
while (scan1.hasNextInt()) {
int i = scan1.nextInt(); // get the number (assuming only int value)
if (i == -1) break;
min = Math.min(i, min);
max = Math.max(i, max);
sum += i;
count++;
}
if (count > 0) {
System.out.println("min " + min);
System.out.println("max " + max);
System.out.println("avg " + sum / count);
}
disclaimer
This code will not handle wrong type of input e.g. Strings
edit
If you want the average to be calculated in a separate method you can have a method like
double calcAvg (double sum, int count) {
return sum / count;
}
this can then be called as
if (count > 0) {
System.out.println("min " + min);
System.out.println("max " + max);
System.out.println("avg " + calcAvg (sum, count));
}
You can (and should) divide your problem into the smaller methods.
I'll drop the code, and you read and study it.
I admit I haven't pay to much attention of this simple quest, but still...
Here you are:
import java.util.List;
public class Answer {
public static void main(String[] args) {
//test with some grades (integers)
Answer answer = new Answer();
List<Integer> someGrades = List.of(12, 66, 34, 96, 3, 77, 2);
System.out.println("max = " + answer.findMaxGrade(someGrades));
System.out.println("min = " + answer.findMinGrade(someGrades));
System.out.println("avg = " + answer.findAverageGrade(someGrades));
}
private int findMaxGrade(List<Integer> grades) {
int max = Integer.MIN_VALUE;
for (int grade : grades) {
if (grade > max) max = grade;
}
return max;
}
private int findMinGrade(List<Integer> grades) {
int min = Integer.MAX_VALUE;
for (int grade : grades) {
if (grade < min) min = grade;
}
return min;
}
private double findAverageGrade(List<Integer> grades) {
double average = 0;
for (int grade : grades) {
average += grade;
}
return average / grades.size();
}
}
package example;
import java.util.Scanner;
class Example {
public static void main(String[] args) {
Scanner r = new Scanner(System.in);
int m = 1, total = 0, max = 0, min = 100;
double avg = 0;
while (m <= 5) {
System.out.print("Input marks " + m + " = ");
int inp = r.nextInt();
total += inp;
m++;
min=min<inp?min:inp;
max=max<inp?inp:max;
}
avg = (double)(total) / 5;
System.out.println("Total : " + total);
System.out.println("Max : " + max);
System.out.println("Min : " + min);
System.out.println("Average : " + avg);
}
}

Java | how can I use multiple methods to print out grade scores?

import java.util.Scanner;
public class BA4 {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Hello Drews, how many total grades do you want to process?");
int numberOfGrades = keyboard.nextInt();
int[] storeGrades = new int[numberOfGrades];
for (int i = 0; i < numberOfGrades; i++) {
System.out.println("Please enter grade " + (i + 1) + ": ");
storeGrades[i] = keyboard.nextInt();
}
System.out.println("Total score is: " + (getTotalScore(storeGrades)));
System.out.println("Lowest score is: " + (getLowestScore(storeGrades)));
System.out.println("Highest score is: " + (getHighestScore(storeGrades)));
System.out.println("Average score is: " + (averageScore(String.format("%.2f", storeGrades))));
}
public static int getTotalScore(int[] storeGrades) {
int sum = 0;
for (int i = 0; i < storeGrades.length; i++) {
sum += storeGrades[i];
}
return sum;
}
public static int getLowestScore(int[] storeGrades) {
int getLowestScore = 0;
for (int i = 0; i > storeGrades.length; i++) {
getLowestScore = storeGrades[i];
}
return getLowestScore;
}
public static int getHighestScore(int[] storeGrades) {
int getHighestScore = 0;
for (int i = 0; i < storeGrades.length; i++) {
getHighestScore = storeGrades[i];
}
return getHighestScore;
}
public static double averageScore(double[] storeGrades) {
double averageScore = 0;
for (int i = 0; i < storeGrades.length; i++) {
averageScore = (double) storeGrades[i];
}
return averageScore;
}
public static int printGrade(int[] storeGrades) {
int printGrade;
if (printGrade > 89) {
String gradeSoFar = "A";
System.out.println("Your grade so far is an " + gradeSoFar);
}
else if ((printGrade > 79) && (printGrade < 90)) {
String gradeSoFar = "B";
System.out.println("Your grade so far is a " + gradeSoFar);
}
else if ((printGrade > 69) && (printGrade < 80)) {
String gradeSoFar = "C";
System.out.println("Your grade so far is a " + gradeSoFar);
}
else if ((printGrade > 59) && (printGrade < 70)) {
String gradeSoFar = "D";
System.out.println("Your grade so far is a " + gradeSoFar);
}
else if ((printGrade > 0) && (printGrade < 60)) {
String gradeSoFar = "F";
System.out.println("Your grade so far is an " + gradeSoFar);
}
return printGrade;
}
}
I am trying to figure out where I am going wrong. I have a couple of errors which leads me to believe I really just don't understand methods as well as I thought I did.
The goal is to create 5 methods displaying to the user the total, lowest, highest and average scores, and then to print the letter grade. Thank you for your assistance to this noobie java coder! :)
You are passing in a String when you should be passing in a Double[] into averageScore function in this line:
System.out.println("Average score is: " + (averageScore(String.format("%.2f", storeGrades))));
and you did not initialize the printGrade variable inside the printGrade function, you need to give it an initial value if you are going to use it in a comparison.
That's all the errors that

Calling getter from imported class

I am having trouble calling a getter from an imported class.
I have created a working class (Students) and an action class (ProgressReport). The main class reads a text file and writes the data to an array. The data is then manipulated in the working class. Last, ProgressReport.generateReport will create a report giving the students name, their grade average and the letter grade associate with that average.
I am having trouble using the Students getters from the Progress Report class. Eclipse is saying the method is undefined. I am not exactly sure what I have done wrong or how to go about fixing it. Any help would be very much appreciated.NOTE: I added some println to make sure parts of the code were being executed. Thank you all in advance.
Code to follow:
Progress Report
package Lab1A;
import java.util.*;
import Lab1A.Students;
import java.io.*;
public class ProgressReport {
public Students section[][];
public static void main(String[] args) throws IOException
{
Students tmpStudent;
ProgressReport progressReport = new ProgressReport();
progressReport.readInputFile();
progressReport.generateReport();
System.out.println("\nSEARCH TEST");
tmpStudent = null;
tmpStudent = progressReport.sequentialSearch(0, "Cooper");
if (tmpStudent != null)
System.out.println("Found " + tmpStudent.getName() +
"\tAverage = " + tmpStudent.getAverage() +
"\tGrade = " + tmpStudent.getGrade());
else System.out.println("Fail to find the student");
tmpStudent = null;
tmpStudent = progressReport.sequentialSearch(0, "Bronson");
if (tmpStudent != null)
System.out.println("Found " + tmpStudent.getName() +
"\tAverage = " + tmpStudent.getAverage() +
"\tGrade = " + tmpStudent.getGrade());
else System.out.println("Fail to find the student");
tmpStudent = null;
tmpStudent = progressReport.sequentialSearch(1, "Diana");
if (tmpStudent != null)
System.out.println("Found " + tmpStudent.getName() +
"\tAverage = " + tmpStudent.getAverage() +
"\tGrade = " + tmpStudent.getGrade());
else System.out.println("Fail to find the student");
}
public ProgressReport()
{
section = new Students [2][];
}
public void readInputFile() throws FileNotFoundException
{
System.out.println("in readInputFile method");
//Open file
File input = new File("Lab1A.in");
Scanner inputFile = new Scanner(input);
System.out.println("file is open");
//Read file data
int currentStudent = 0;
while (inputFile.hasNext())
{
System.out.println("In while loop");
//Get Student count
int rows = inputFile.nextInt();
//Read student data
section[currentStudent] = new Students[rows];
System.out.println("array initiated");
for(int i = 0; i < rows; i++)
{
System.out.println("In for loop");
//read in a students info
String sName = inputFile.next();
//Read in grades
int grade1 = inputFile.nextInt();
int grade2 = inputFile.nextInt();
int grade3 = inputFile.nextInt();
int grade4 = inputFile.nextInt();
int grade5 = inputFile.nextInt();
//Send to Students Array
section[currentStudent][i] = new Students(sName, grade1, grade2, grade3, grade4, grade5);
}
//Next Student Line
currentStudent++;
}
inputFile.close();
}
public void generateReport()
{
System.out.println("Progress Report");
double average = Students.class.getAverage();
//String section = "Section\n";
}
public Students sequentialSearch(int section, String searchName)
{
return null;
}
}
Students Class
package Lab1A;
import java.lang.reflect.Array;
public class Students {
private String name;
private char grade;
private double average;
private int scores[];
public Students(String sName, int grade1, int grade2, int grade3, int grade4, int grade5)
{
//CONSTRUCTOR load data from ProgressReport
name = sName;
int newScores[] = {grade1, grade2, grade3, grade4, grade5};
scores = newScores;
}
//Getters and Setters
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public char getGrade() {
if(average >= 90 && average <= 100)
{
grade = 'A';
}
if(average >= 80 && average < 90)
{
grade = 'B';
}
if(average >= 70 && average < 80)
{
grade = 'C';
}
if(average >= 60 && average < 70)
{
grade = 'D';
}
if(average >= 0 && average < 60)
{
grade = 'F';
}
return grade;
}
public void setGrade(char grade) {
this.grade = grade;
}
public double getAverage() {
return average;
}
public void setAverage(double average) {
this.average = average;
}
public int[] getScores() {
return scores;
}
public void setScores(int[] scores) {
this.scores = scores;
}
//Calculate average score
public void calculateAverage()
{
int total = 0;
for (int i = 0; i < scores.length; i++)
{
total += scores[i];
}
average = total*1.0/scores.length;
}
//calculate letter grade based on average score (calulateAverage.average)
public void calculateGrade()
{
if(average >= 90 && average <= 100)
{
grade = 'A';
}
if(average >= 80 && average < 90)
{
grade = 'B';
}
if(average >= 70 && average < 80)
{
grade = 'C';
}
if(average >= 60 && average < 70)
{
grade = 'D';
}
if(average >= 0 && average < 60)
{
grade = 'F';
}
}
}
Your not specifying which Student you want the average of (Not sure why you named your class students with an s). It needs to look something like this:
section[1][1].getAverage()

Calling a method from another class with setters and getters in Java

I need some help with this as I'm completely lost. I'm trying to call a method I created in another class to output what the grade is for the average entered by the user, but I'm not sure where I messed up. I don't get how to call my other class, I read that using an object as a variable doesn't work in Java, but I have no clue how else to get it to pull through to apply the method in the other class to give the correct grade.
Here's the class that contains the method....
public class Assignment {
private double score;
public double getScore(){
return score;
}
public void setScore(double newScore){
score = newScore;
}
public static void newScore(double a, double b, double c, double d, double f) {
double score1 = a;
double score2 = b;
double score3 = c;
double score4 = d;
double score5 = f;
if (score1 >= 90) {
System.out.println("Your grade is: " + score1);
System.out.println("Great job!");
} else if (score2 >= 80 && score2 < 90) {
System.out.println("Your grade is: " + score2);
System.out.println("Not bad!");
} else if (score3 >= 70 && score3 < 80) {
System.out.println("Your grade is: " + score3);
System.out.println("Need a little work");
} else if (score4 >= 60 && score4 < 70) {
System.out.println("Your grade is: " + score4);
System.out.println("Not looking so good.");
} else if (score5 >= 50 && score5 < 60) {
System.out.println("Your grade is: " + score5);
System.out.print("Study harder!");
} else {
System.out.println("Yikes!");
}
}
}
And here's what I put in the main method...
import java.util.Scanner;
public class Grades {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Assignment newScore = new Assignment ();
System.out.println("Enter your test score: ");
newScore = input.nextDouble();
System.out.println("Your current grade is: " + newScore);
}
}
Don't quite understand your question here. You have a method that takes in multiple score, and it has a set of if-else statements to determine the message to print based off;
if first score is more than 90 do this,
and if first score's condition is not met, then check second score value.
and then if second condition not met, then check third score to see if it met certain score.. blah blah
If you are looking at having an assignment class to keep a set of scores and finally print out each score then do this;
Modify your Assignment class is to allow multiple scores to be kept at a time. To be able to hold multiple scores you will have to change the score variable to be at least an array or a list. That is, List<Double> scores = new ArrayList<Double>();
Then modify the setter method to be something like "addScore(double score)"
public void addScore(double score) {
scores.add(score)
}
In your "newScore" method, use a loop to iterate through the score to output the appropriate score message for each assignment.
for (Double score : scores) {
if (score > 90) {
System.out.println('blah');
}
}
Note the code above are just something I type off my mind, I didn't test it using any compilers so you may have to rework on some syntax errors.
Since the variable newScore is a Assignment object rather than a double, the code newScore = input.nextDouble(); can not be compiled. I suppose you are using the input number as your score, so that line should be
newScore.setScore(input.nextDouble());
Hence the next line should be
System.out.println("Your current grade is: " + newScore.getScore());
Kindly replace these two lines and check if it suites your requirements.
EDIT:
Assignment.java:
public class Assignment {
private double score;
public double getScore(){
return score;
}
public void setScore(double newScore){
score = newScore;
}
public void checkScore(double a, double b, double c, double d, double f) {
if (score >= a) {
System.out.println("Your grade is: " + score);
System.out.println("Great job!");
} else if (score >= b && score < a) {
System.out.println("Your grade is: " + score);
System.out.println("Not bad!");
} else if (score >= c && score < b) {
System.out.println("Your grade is: " + score);
System.out.println("Need a little work");
} else if (score >= d && score < c) {
System.out.println("Your grade is: " + score);
System.out.println("Not looking so good.");
} else if (score >= f && score < d) {
System.out.println("Your grade is: " + score);
System.out.print("Study harder!");
} else {
System.out.println("Yikes!");
}
}
}
Grades.java:
import java.util.Scanner;
public class Grades {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Assignment newScore = new Assignment();
System.out.println("Enter your test score: ");
newScore.setScore(input.nextDouble());
newScore.checkScore(90, 80, 70, 60, 50);
System.out.println("Your current grade is: " + newScore.getScore());
}
}

Polymorphism and instanceof

I have programed a Worker and MachineWorker class. It complies fine. but when i run it, after three consecutive statements the program stops. I cannot find the problem, and I dont know how and when to use 'instanceof'.
I am writing the question below and with all the classes...
Question:- (i)Declare an array that can store the references of up to 5 Worker or MachineWorker objects.
a)Allow user to enter the type of object and the data for that type of object(3 values for Worker and 4 values for MachineWorker).
b)Construct the appropriate object storing the reference in the common array.
ii)Now allow the users to enter the weekly data repeatedly. If it is Worker object user must enter ID and hours-worked. If it is a MachineWorker object user must enter ID,hoursWorked and pieces. Once these values read search through the array to locate the object with the given ID before calling the addWeekly().The number of arguments either(1 or 2) to be passed to addWeekly depends on the type of objects being referred. To determine the type of object being referred(Worker or MachineWorker)you may use the instanceof operator.
Please see my codes below:-
//Worker.java
public class Worker {
public final double bonus=100;
protected String name, workerID;
protected double hourlyRate, totalHoursWorked,tax,grossSalary,netSalary;
public Worker(){
}
public Worker(String name, String workerID, double hourlyRate){
this.name = name;
this.workerID = workerID;
this.hourlyRate = hourlyRate;
}
public void addWeekly(double hoursWorked){
this.totalHoursWorked = this.totalHoursWorked + hoursWorked;
}
public double gross(){
grossSalary = (totalHoursWorked*hourlyRate);
if(totalHoursWorked>=150){
grossSalary = grossSalary +100;
}
return grossSalary;
}
public double netAndTax(){
netSalary = grossSalary;
if(grossSalary>500){
tax = (grossSalary - 500) *0.3;
netSalary = (grossSalary - tax);
}
return netSalary;
}
public String getName(){
return this.name;
}
public String getWorkerID(){
return this.workerID;
}
public double getHourlyRate(){
return this.hourlyRate;
}
public double getTotalHours(){
return totalHoursWorked;
}
public double getGrossSalary(){
return grossSalary;
}
public void addToGross(double amt){
grossSalary = grossSalary + amt;
}
public void displaySalary(){
System.out.print("Name: " +getName() + "\nID :" + getWorkerID()
+ "\nHourly Rate: " + getHourlyRate()+ "\nTotalHours Worked" + getTotalHours() +
"\nGross pay" + getGrossSalary() + "\nTax: " + netAndTax() +
"\nNet Pay: " + netAndTax());
}
}
//MachineWorker.java
public class MachineWorker extends Worker{
private double targetAmount;
private double totalPieces, productivityBonus;
public MachineWorker(String workerName, String workerID, double hourlyRate, double targetAmount)
{
super(workerName, workerID, hourlyRate);
//this.productivityBonus = productivityBonus;
this.targetAmount = targetAmount;
}
public void addWeekly(double hoursWorked, double weeklyAmount)
{
totalHoursWorked = hoursWorked + totalHoursWorked;
totalPieces = weeklyAmount + totalPieces;
}
public double productivityBonus()
{
productivityBonus = 100 + (totalPieces - targetAmount);
return productivityBonus;
}
public double gross()
{
grossSalary = (totalHoursWorked * hourlyRate) + productivityBonus;
if(totalHoursWorked >= 150)
{
grossSalary = grossSalary + bonus;
}
return grossSalary;
}
public void addToGross(double amt)
{
amt = productivityBonus;
grossSalary = grossSalary + amt;
}
public void displaySalary()
{
System.out.println("Name " + super.name + "\nID " +
super.workerID + "\nHourly rate " + super.hourlyRate + "\nTotal Hours Worked " +
super.totalHoursWorked + "\nGross Pay $" + super.grossSalary + "\nTax $" + super.tax + "\nNetpay $" + super.netSalary);
System.out.println("Productivity Bonus " + productivityBonus);
}
}
//Polymorphism PolyWorker.java
import java.util.*;
public class PolyWorkers
{
public static void main(String args[])
{
Scanner input = new Scanner(System.in);
Worker[] a = new Worker[5];
MachineWorker[] b = new MachineWorker[5];
char option = '0';
String choice;
boolean nChar = false;
for (int i = 0; i < 5; i++){
System.out.print("\tType of object " + (i+1) + " [W/M]: ");
choice = input.nextLine();
if (choice.length() == 1)
{
option = choice.charAt(0); //pick the first character
if (option == 'w' || option == 'W')
{
System.out.println("\n\tEnter name, ID and hours: ");
String name = input.nextLine();
System.out.print(" ");
String id = input.nextLine();
System.out.print(" ");
double hours = input.nextDouble();
a[i] = new Worker(name, id, hours);
System.out.println();
}
if (option == 'm' || option == 'M')
{
System.out.print("\n\tEnter name, ID, hours and pieces: ");
String name = input.nextLine();
System.out.print(" ");
String id = input.nextLine();
System.out.print(" ");
double hours = input.nextDouble();
System.out.print(" ");
double pieces = input.nextDouble();
b[i] = new MachineWorker(name, id, hours, pieces);
System.out.println();
}
System.out.print("\tType of object " + (i+1) + " [W/M]: ");
choice = input.nextLine();
}
a[i].displaySalary();
b[i].displaySalary();
b[i].productivityBonus();
}
}
}
You might want to use overriden methods readfromInput and displaySalary to distinguish between what Worker and Machinworker does.
The different behaviour should be implemented within the classes and not in the calling Polyworker class.
If Machineworker displaySalary shows the bonus this should be called in displaySalary of MachineWorker
see modified code below
//Worker.java
import java.util.Scanner;
/**
* a generic worker
*/
public class Worker {
public final double bonus = 100;
protected String name, workerID;
protected double hourlyRate, totalHoursWorked, tax, grossSalary, netSalary;
public void addWeekly(double hoursWorked) {
this.totalHoursWorked = this.totalHoursWorked + hoursWorked;
}
public double gross() {
grossSalary = (totalHoursWorked * hourlyRate);
if (totalHoursWorked >= 150) {
grossSalary = grossSalary + 100;
}
return grossSalary;
}
public double netAndTax() {
netSalary = grossSalary;
if (grossSalary > 500) {
tax = (grossSalary - 500) * 0.3;
netSalary = (grossSalary - tax);
}
return netSalary;
}
public String getName() {
return this.name;
}
public String getWorkerID() {
return this.workerID;
}
public double getHourlyRate() {
return this.hourlyRate;
}
public double getTotalHours() {
return totalHoursWorked;
}
public double getGrossSalary() {
return grossSalary;
}
public void addToGross(double amt) {
grossSalary = grossSalary + amt;
}
public void displaySalary() {
System.out.print("Name: " + getName() + "\nID :" + getWorkerID()
+ "\nHourly Rate: " + getHourlyRate() + "\nTotalHours Worked"
+ getTotalHours() + "\nGross pay" + getGrossSalary() + "\nTax: "
+ netAndTax() + "\nNet Pay: " + netAndTax());
}
public void readFromInput(Scanner input) {
name = input.nextLine();
System.out.print(" ");
this.workerID= input.nextLine();
System.out.print(" ");
this.totalHoursWorked = input.nextDouble();
System.out.println();
}
} // Worker
//MachineWorker.java
import java.util.Scanner;
public class MachineWorker extends Worker {
private double targetAmount;
private double totalPieces, productivityBonus;
public void addWeekly(double hoursWorked, double weeklyAmount) {
totalHoursWorked = hoursWorked + totalHoursWorked;
totalPieces = weeklyAmount + totalPieces;
}
public double productivityBonus() {
productivityBonus = 100 + (totalPieces - targetAmount);
return productivityBonus;
}
public double gross() {
grossSalary = (totalHoursWorked * hourlyRate) + productivityBonus;
if (totalHoursWorked >= 150) {
grossSalary = grossSalary + bonus;
}
return grossSalary;
}
public void addToGross(double amt) {
amt = productivityBonus;
grossSalary = grossSalary + amt;
}
#Override
public void displaySalary() {
super.displaySalary();
System.out.println("Productivity Bonus " + productivityBonus);
}
#Override
public void readFromInput(Scanner input) {
super.readFromInput(input);
this.totalPieces = input.nextDouble();
}
}
//Polymorphism PolyWorker.java
import java.util.*;
public class PolyWorkers {
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
Worker[] workers = new Worker[5];
char option = '0';
String choice;
for (int i = 0; i < 5; i++) {
System.out.print("\tType of object " + (i + 1) + " [W/M]: ");
choice = input.nextLine();
if (choice.length() == 1) {
option = choice.toLowerCase().charAt(0); // pick the first character
switch (option) {
case 'w': {
workers[i] = new Worker();
System.out.println("\n\tEnter name, ID and hours: ");
}
break;
case 'm': {
System.out.print("\n\tEnter name, ID, hours and pieces: ");
}
break;
} // switch
workers[i].readFromInput(input);
}
workers[i].displaySalary();
}
}
}
Your question states that you have to store the references in a common array, where as you are storing them in 2 different arrays a and b. As you have different arrays for different type of objects, you don't have the need to use instanceOf operator. More about instanceOf is here.
Also, you do not check for null while printing salary or bonus. As at any point of the loop, only one type of object will be created, one of a[i] or b[i] will be definitely null, causing a NullPointerException.
You need another loop after the one you have already written that will allow the user to input the worker's hours. This will presumably be a while loop that will continually ask for input. You would then choose some sort of input that would quit the loop. Inside the loop you ask for hours and take either 2 or 3 arguments.
At the moment you are not storing your Workers/MachineWorkers. You need to create an array to store them in. You also need to create either a base class or an interface that they will both extend/implement. This will allow you to create a single array to store them all.
You then loop through your array of Workers/MachineWorkers and when you find a matching id you use your instanceof to work out whether you need to pass 1 or 2 arguments. If it is a MachineWorker you should cast it as such and then call the appropriate method with 2 arguments.

Categories

Resources