I am using BlueJ, for reference.
The program compiles fine. It runs fine as well except that this:
java.lang.NumberFormatException: For input string: "Washington,George"
at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:2043)
at sun.misc.FloatingDecimal.parseDouble(FloatingDecimal.java:110)
at java.lang.Double.parseDouble(Double.java:538)
at WorkerApp.main(WorkerApp.java:53)
at __SHELL112.run(__SHELL112.java:6)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at bluej.runtime.ExecServer$3.run(ExecServer.java:730)
Specifically highlighting:
java.lang.NumberFormatException: For input string: "Washington,George"
at WorkerApp.main(WorkerApp.java:53)
The point of this program is to read a text file and add to said text file.
The program is supposed to read and open "EmployeeData.txt":
S Washington,George 000001 125000
H MacDonald,Ronald 386218 7.80 true 40
H Walton,Samuel 268517 8.21 false
H Thomas,David 131313 9.45 true 38
H Sanders,HarlandDavid 277651 8.72 false
S Baron,James 368535 310236
When I click on the exception it highlights this from my main class
double salary = Double.parseDouble(Employee[3]);
This is the full main class WorkerApp in which I am trying to read and open the text file:
import java.io.*;
import java.util.*;
public class WorkerApp{
/**
* Reads the infile, runs tests, and prints the output.
*/
public static void main (String args[]){
Company company = new Company();
try{
Scanner reader = new Scanner (new File("EmployeeData.txt"));
while(reader.hasNext()){
String line = reader.nextLine();
String Employee[] = line.split(" ");
String sorh = Employee[0];
String name = Employee[1];
String id = Employee[2];
double salary = Double.parseDouble(Employee[3]);
Employee e;
if (Employee[0].equals("S")){
e = new SalariedWorker(sorh, name, id, salary);}
else {
boolean overtime = Boolean.parseBoolean(Employee[4]);
if(overtime){
int maxHours = Integer.parseInt(Employee[5]);
e = new HourlyWorker(sorh, name, id, salary, maxHours);
}
else{
e = new HourlyWorker(sorh, name, id, salary);
}
}
company.add(e);
}
}catch (Exception err){
//System.out.println(err);
err.printStackTrace();
}
company.print();
System.out.println();
//Test Number 1
System.out.println("1) Add a salaried worker");
SalariedWorker SWorker1 = new SalariedWorker("S", "Moran,Blake", "123456", 260000);
company.add(SWorker1);
company.print();
//Test Number 2
System.out.println("2) Add an hourly worker who has no overtime allowed");
HourlyWorker HWorker1 = new HourlyWorker("H", "Bob,Billy", "654321", 15);
company.add(HWorker1);
company.print();
//Test Number 3
System.out.println("3) Add an hourly worker who has overtime allowed");
HourlyWorker HWorker2 = new HourlyWorker("H", "Smith,Will", "345612", 10.5, 30);
company.add(HWorker2);
company.print();
//Test Number 4
System.out.println("4) Add a worker that is already in the database");
try{
company.add(SWorker1);
}catch(Exception err){
System.out.println(err);
System.out.println();
}
//Test Number 5
System.out.println("5) Print the sorted list");
company.print();
//Test Number 6
System.out.println("6) Remove a worker who is NOT in the list");
company.remove("Brooks,Phil");
System.out.println();
//Test Number 7
System.out.println("7) Remove a worker who is the first in the list ");
company.remove("Moran,Blake");
company.print();
System.out.println();
//Test Number 8
System.out.println("8) Find a worker who is the middle of the list");
int index = company.find("Bob,Billy");
System.out.println("Found at "+ index);
System.out.println();
//Test Number 9
System.out.println("9) Find a worker who is NOT in the list");
index = company.find("Harrison,Ford");
System.out.println("Found at "+ index);
System.out.println();
//Test Number 10
System.out.println("10) Find the weekly salary of a worker who is salaried");
System.out.println(SWorker1.FindSalary());
System.out.println();
//Test Number 11
System.out.println("11) Find the weekly salary of an hourly worker who has no overtime allowed [50 hours]");
System.out.println(HWorker1.FindSalary(50));
System.out.println();
//Test Number 12
System.out.println("12) Find the weekly salary of an hourly worker who has overtime allowed [50 hours]");
System.out.println(HWorker2.FindSalary(50));
System.out.println();
//Test Number 13
System.out.println("13) Find the weekly salary of an hourly worker who has overtime allowed [20 hours]");
System.out.println(HWorker2.FindSalary(20));
System.out.println();
//Test Number 14
System.out.println("14) Print the sorted list");
company.print();
//Test Number 15
System.out.println("\n15) End the process");
}
}
It should be noted that on top of the exception it spits out this output:
1) Add a salaried worker
S Moran,Blake 123456 260000.0
2) Add an hourly worker who has no overtime allowed
S Moran,Blake 123456 260000.0
H Bob,Billy 654321 15.0 false
3) Add an hourly worker who has overtime allowed
S Moran,Blake 123456 260000.0
H Bob,Billy 654321 15.0 false
H Smith,Will 345612 10.5 true 30
4) Add a worker that is already in the database
java.lang.RuntimeException: The Employee Is Not New
5) Print the sorted list
S Moran,Blake 123456 260000.0
H Bob,Billy 654321 15.0 false
H Smith,Will 345612 10.5 true 30
6) Remove a worker who is NOT in the list
The Employee is not Found
7) Remove a worker who is the first in the list
H Bob,Billy 654321 15.0 false
H Smith,Will 345612 10.5 true 30
8) Find a worker who is the middle of the list
Found at 0
9) Find a worker who is NOT in the list
Found at -1
10) Find the weekly salary of a worker who is salaried
5000.0
11) Find the weekly salary of an hourly worker who has no overtime allowed [50 hours]
750.0
12) Find the weekly salary of an hourly worker who has overtime allowed [50 hours]
630.0
13) Find the weekly salary of an hourly worker who has overtime allowed [20 hours]
210.0
14) Print the sorted list
H Bob,Billy 654321 15.0 false
H Smith,Will 345612 10.5 true 30
15) End the process
If it helps, here are my other classes for reference, as they might be the source of the problem.
Company:
import java.io.*;
import java.util.*;
public class Company{
private Employee[] employeeArray;
private final int InitialCapacity = 7;
private int employCount;
/**
* Creates the employee array and sets employCount to 0.
*/
public Company(){
employeeArray = new Employee[InitialCapacity];
employCount = 0;
}
/**
* Finds an employee in the list.
*/
public int find(String name){
for (int i = 0; i < employCount; i++){
if (employeeArray[i].getName().equals(name)){
return i;
}
}
return -1;
}
/**
* Adds an employee to the list.
*/
public int add(Employee employ){
int index;
for (index = 0; index < employCount; index++){
int result = employeeArray[index].getName().compareTo(employ.getName());
if(result == 0){
throw new RuntimeException ("The Employee Is Not New");
}
}
if (employeeArray.length == employCount){
expand();
}
employeeArray[index] = employ;
employCount++;
return index;
}
/**
* Removes an employee to the list.
*/
public void remove(String name){
int index = find(name);
if (index == -1){
System.out.println("The Employee is not Found");
return;
}
for (int i = index; i < employCount - 1; i++){
employeeArray[i] = employeeArray[i + 1];
}
employCount--;
}
/**
* Prints the list.
*/
public void print(){
if(employCount == 0){
System.out.println("The List is Empty");
return;
}
for(int i = 0; i < employCount; i++){
System.out.println(employeeArray[i]);
}
}
/**
* Expands the list.
*/
private void expand(){
Employee[] newArray = new Employee[employeeArray.length + InitialCapacity];
for (int i = 0; i < employeeArray.length; i++){
newArray[i] = employeeArray[i];
}
employeeArray = newArray;
}
}
Employee:
import java.io.*;
import java.util.*;
public class Employee{
private String SorH;
private String name;
private String ID;
/**
* Sets sets SorH, name, and ID to SH, n, and id.
*/
public Employee (String SH, String n, String id){
SorH = SH;
name = n;
ID = id;
}
/**
* Gets the first part (S or H) of the employee list.
*/
public String getSorH(){
return SorH;
}
/**
* Gets the name of the employee list.
*/
public String getName(){
return name;
}
/**
* Gets the ID of the employee list.
*/
public String getID(){
return ID;
}
/**
* Sets SorH to SH.
*/
public void setSorH(String SH){
SorH = SH;
}
/**
* Sets name to n.
*/
public void setName(String n){
name = n;
}
/**
* Sets ID to id.
*/
public void setID(String id){
ID = id;
}
/**
* Returns a string representing the employee list.
*/
public String toString(){
return String.format("%s %s %s", getSorH(), getName(), getID());
}
}
HourlyWorker:
import java.io.*;
import java.util.*;
public class HourlyWorker extends Employee{
private double hourlySalary;
private boolean overtime;
private int maxHours;
/**
* Contains the super and sets the hourly salary and maxHours to hourlySal and maxH and
* overtime to true.
*/
public HourlyWorker(String SH, String n, String id, double hourlySal, int maxH){
super(SH, n, id);
hourlySalary = hourlySal;
overtime = true;
maxHours = maxH;
}
/**
* Contains the super and sets the hourly salary to hourlySal and overtime to false.
*/
public HourlyWorker(String SH, String n, String id, double hourlySal){
super(SH, n, id);
hourlySalary = hourlySal;
overtime = false;
}
/**
* Returns if overtime is true or false.
*/
public boolean overtime(){
return overtime;
}
/**
* Gets the max hours of an hourly worker.
*/
public int getmaxH(){
return maxHours;
}
/**
* Gets the hourly salary of an hourly worker.
*/
public double gethourlySalary(){
return hourlySalary;
}
/**
* Sets hourly salary to hSalary.
*/
public void sethourlySalary (double hSalary){
hourlySalary = hSalary;
}
/**
* Finds the weekly salary of an hourly worker.
*/
public double FindSalary(double hoursWorked){
if (overtime){
if (hoursWorked <= maxHours){
return hoursWorked * hourlySalary;
} else{
return maxHours * hourlySalary +
(hoursWorked - maxHours) * hourlySalary * 1.5;
}
} else{
return hoursWorked * hourlySalary;
}
}
/**
* Contains the super string and adds onto the string.
*/
public String toString(){
String str = super.toString() + String.format(" %s %s", gethourlySalary(),overtime());
if (overtime){
str = str + String.format(" %s", getmaxH());
}
return str;
}
}
SalariedWorker:
import java.io.*;
import java.util.*;
public class SalariedWorker extends Employee{
private double yearlySalary;
/**
* Contains the super and sets yearly salary to ySalary.
*/
public SalariedWorker(String SH, String n, String id, double ySalary){
super(SH, n, id);
yearlySalary = ySalary;
}
/**
* Gets the yearly salary of a salaried worker.
*/
public double getyearlySalary(){
return yearlySalary;
}
/**
* Sets the yearly salary of a salaried worker.
*/
public void setyearlySalary(double ySalary){
yearlySalary = ySalary;
}
/**
* Finds the weekly salary of a salaried worker.
*/
public double FindSalary(){
return yearlySalary / 52;
}
/**
* Contains the super string and adds onto the string.
*/
public String toString(){
return super.toString() + String.format(" %s", getyearlySalary());
}
}
Thank you in advance!
Instead of line.split(" "); you might want to try line.split("\\s+"). I think the splitting is not happening properly.
Don't you have access to a debugger ? There should be one in any IDE you can use, be it Netbeans, Eclipse, IntelliJ or ...
Just put a breakpoint on the line where exception occurs and look at the values in the Employee array. The cause of the error should then be self evident.
In case it is still not evident for you, here is next clue : read again the javadoc for String.split() and compare with what you have in Employee.
Related
I want my array of students to have their name and grade associated. So when I call on them after the fact I can display the top two performing students. This is homework So I don't need to have the whole code completed but I would like some help with making sure the inputs are properly stored. Right now my variables are x and i, x being the number of students, and i being the counter. Again my issues are with associating the grades of the students inputted with the names. I hope there is enough information.
import java.util.Scanner;
public class Q3 {
public static void main(String[] args) {
int x = 0;
double average = 0;
int i = 0;
Scanner in = new Scanner(System.in);
System.out.println("Please eneter how many students you have: ");
x = in.nextInt();
int students = 0;
int sum = 0;
int grades[] = new int[x];
String[] names = new String[x];
for(i = 0; i <= x; i++) {
System.out.println("Please enter student name: ");
String name = in.nextLine();
names[i] = name;
System.out.println("Grade: ");
int grade = in.nextInt();
grades[i] = grade;
students++;
sum += grade;
x++;
}
if(students>0) {
average = (double) sum/students;
}
System.out.println("The average is " + average);
System.out.println("There are " + students + " students");
System.out.println("The top two students are: " + grades);
}
}
The problem with your current code is that the for loop will never end, as you keep increasing the value of x, which is also used in the end condition.
Here are some suggestions:
Just store the number of students when you read it and remove the x variable:
int students = in.nextInt();
int grades[] = new int[students ];
String[] names = new String[students ];
Then read in this number of sudents:
for(i = 0; i < students; i++) {
To find the top two students you'd use the following logic (assumes 2 or more students)
if grade[0] >= grade[1]
max1 = 0
max2 = 1
else
max1 = 1
max2 = 0
for i from 2 to students-1
if grade[i] >= grade[max1]
max2 = max1
max1 = i
else if grade[i] > grade[max2]
max2 = i
The top two students are then at positions max1 and max2 in the names and grades array.
Probably overkill, but maybe someone will find it useful.
I store all the students in a TreeSet. I assume that each student has a unique name. I use a special Comparator to sort the students in the TreeSet according to their grades. A descending Iterator of the TreeSet will return the students from highest grade to lowest grade, so the first two items returned by this Iterator are the top two students.
import java.util.Comparator;
import java.util.Iterator;
import java.util.Scanner;
import java.util.TreeSet;
/**
* A student name and her grade.
*/
public class StudentGrade {
/** Name of student. */
private String studentName;
/** Grade for this student. */
private int studentGrade;
/**
* Creates and returns instance of this class.
*
* #param name - student name
* #param grade - student grade
*/
public StudentGrade(String name, int grade) {
studentName = name;
studentGrade = grade;
}
/**
* #return Student's name.
*/
public String getStudentName() {
return studentName;
}
/**
* #return Student's rgade.
*/
public int getStudentGrade() {
return studentGrade;
}
/**
* Two instances of this class are equal if they both have the same name.
*/
#Override // java.lang.Object
public boolean equals(Object obj) {
boolean isEqual = false;
if (obj != null) {
Class<?> objClass = obj.getClass();
if (objClass.equals(getClass())) {
StudentGrade other = (StudentGrade) obj;
isEqual = studentName.equals(other.getStudentName());
}
}
return isEqual;
}
#Override // java.lang.Object
public int hashCode() {
return studentName.hashCode();
}
#Override // java.lang.Object
public String toString() {
return String.format("%s [%d]", studentName, studentGrade);
}
/**
* Start here.
*/
public static void main(String[] args) {
// Stores all student grades, sorted by grade in ascending order.
TreeSet<StudentGrade> studentSet = new TreeSet<>(new StudentGradeComparator());
Scanner in = new Scanner(System.in);
System.out.print("Please enter how many students you have: ");
int students = in.nextInt();
int index = students;
int sum = 0;
while (index > 0) {
// make sure we consume the newline character since 'nextInt()' does not
in.nextLine();
System.out.print("Enter student name: ");
String name = in.nextLine();
System.out.printf("Enter grade for %s: ", name);
int grade = in.nextInt();
sum += grade;
StudentGrade sg = new StudentGrade(name, grade);
studentSet.add(sg);
index--;
}
double average;
if (students > 0) {
average = (double) sum / students;
}
else {
average = 0.0d;
}
System.out.println("The average is " + average);
String verb = students == 1 ? "is" : "are";
String plural = students == 1 ? "" : "s";
System.out.printf("There %s %d student%s.%n", verb, students, plural);
if (students > 1) {
Iterator<StudentGrade> iter = studentSet.descendingIterator();
System.out.printf("The top two students are: %s, %s%n", iter.next(), iter.next());
}
}
}
/**
* Compares 'StudentGrade' instances according to their grades.
*/
class StudentGradeComparator implements Comparator<StudentGrade> {
/**
* Returns a positive number if 'sg1' grade is larger than that of 'sg2'.
* Returns a negative number if 'sg1' grade is less than that of 'sg2'.
* Returns zero if 'sg1' grade is equal to 'sg2' grade.
*/
#Override
public int compare(StudentGrade sg1, StudentGrade sg2) {
if (sg1 == null) {
if (sg2 != null) {
return -1;
}
else {
return 0;
}
}
else {
if (sg2 == null) {
return 1;
}
else {
return sg1.getStudentGrade() - sg2.getStudentGrade();
}
}
}
}
Here is a sample run:
Please enter how many students you have: 3
Enter student name: George
Enter grade for George: 70
Enter student name: Diego
Enter grade for Diego: 90
Enter student name: Edson
Enter grade for Edson: 65
The average is 75.0
There are 3 students.
The top two students are: Diego [90], George [70]
I am very unexperienced with java and i need help with my school assingment. I am not sure how to get user input. The code was provided to us and we just have to put a ling of code in place of the dotted lines to complete the program but I am stuck.
I have two classes and here they are.
/**
* Write a description of class PhoneBookEntry here.
*
* #author (your name)
* #version (a version number or a date)
*/
public class PhoneBookEntry
{
private String name; // Person's name
private String phoneNumber; // Person's phone number
/**
* The constructor initializes the person's name
* and phone number.
*/
public PhoneBookEntry(String n, String pn)
{
name = n;
phoneNumber = pn;
}
/**
* The setName method sets the person's name.
*/
public void setName(String n)
{
name = n;
}
/**
* setPhoneNumber method sets the person's
* phone number.
*/
public void setPhoneNumber(String pn)
{
phoneNumber = pn;
}
/**
* The getName method returns the person's
* name.
*/
public String getName()
{
return name;
}
/**
* The getPhoneNumber method returns the
* person's phone number.
*/
public String getPhoneNumber()
{
return phoneNumber;
}
}
/**
* Chapter 7
* Lab Assignment: Phone Book ArrayList
* This program demonstrates the PhoneBookEntry class.
*/
public class PhoneBookDemo
{
public static void main(String args[])
{
// Constant for the numer of entries.
final int NUM_ENTRIES = 5;
// Create an ArrayList to hold PhoneBookEntry objects.
ArrayList<PhoneBookEntry> list =
new ArrayList<PhoneBookEntry>();
// Tell the user what's about to happen.
System.out.println("I'm going to ask you to enter " +
NUM_ENTRIES + " names and phone numbers.");
System.out.println();
// Store PhoneBookEntry objects in the ArrayList.
for (int i = 0; i < NUM_ENTRIES; i++)
{
-----------------
System.out.println();
}
System.out.println("Here's the data you entered:");
// Display the data stored in the ArrayList.
for (int i = 0; i < list.size(); i++)
{
System.out.println(list);
}
}
/**
* The getEntry method creates a PhoneBookEntry object
* populated with data entered by the user and returns
* a reference to the object.
*/
public static PhoneBookEntry getEntry()
{
// Create a Scanner object for keyboard input.
Scanner keyboard = new Scanner(System.in);
// Variables to hold a person's name and
// phone number.
String name;
String phoneNumber;
// Get the data.
System.out.print("Enter a person's name: ");
name = keyboard.nextLine();
System.out.print("Enter that person's phone number: ");
phoneNumber = keyboard.nextLine();
// Create a PhoneBookEntry object.
PhoneBookEntry entry = new PhoneBookEntry(name, phoneNumber);
// Return a reference to the object.
return entry;
}
/**
* The displayEntry method displays the data stored
* in a PhoneBookEntry object.
*/
public static void displayEntry(PhoneBookEntry entry)
{
System.out.println("------------------------------");
System.out.println("Name: " + entry.getName());
System.out.println("Phone number: " + entry.getPhoneNumber());
}
}
In the loop (the dotted lines) you just need to add:
list.add(getEntry());
The handling of the stream is already implemented in getEntry() method.
Add this stuff to your code:
outside the Main class:
import java.util.Scanner;
inside the main class
Scanner input = new Scanner(System.in);
System.out.println("Asking for input");
String userResponse = input.nextLine();
For an Int rather than a string:
Int userResponse = input.nextInt();
The program will pause and wait for an input. Then, your userResponse will now contain what the user typed in.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
Working on a java program that computes salaries for a collection of employees of different types, which is imported from a TXT file.
The program builds and runs successfully if I comment out:
System.out.println("\nAverage Salary for 2014: " + (totalSalary / indexYear2014));
System.out.println("\nAverage Salary for 2015: " + (totalSalary / indexYear2015));
However, it does not seem that the data is imported/used at all.
Here is the full code:
package computeemployeesalary;
/**
*
* #author Jason Snook
* Course name: Intermediate Programming (CMIS 242)
* Assignment: Project 1 - Compute Employee Salary
*/
/**
* This program computes the salaries of a collection of employees of
* different types: Employee, Salesman, Executive
*
* Salary for employee is calculated by multiplying monthly salary by 12
*
* Salary for salesman takes the base of employee, and then adds commission,
* which has a cap of 20000
*
* Salary for executive takes the base of employee, and then adds a bonus
* in the event that the current stock is more than 100
*/
// Imports
import java.util.Scanner;
import java.io.*;
/**
* This class contains the employee name and monthly salary
*/
// Employee class
class Employee {
// Variable declaration
String employeeName;
int monthlySalary = 0;
// Employee constructor
public Employee(String employeeName, int monthlySalary) {
this.employeeName = employeeName;
this.monthlySalary = monthlySalary;
} // end Employee constructor method
// Calculate employee annual salary
public int annualSalary() {
return monthlySalary * 12;
} // end annualSalary method
// Return employee name and annual salary as String
#Override // takes advantage from compiler checking
public String toString() {
return "Employee Name: " + employeeName +
" Salary: $" + monthlySalary;
} // end toString method
} // end employee class
/**
* This class contains the salesman annual sales and extends employee class
*/
// Salesman subclass, extends Employee class
class Salesman extends Employee {
// Variable declaration
int annualSales = 0;
// Salesman constructor
public Salesman(String employeeName, int monthlySalary, int annualSales) {
super(employeeName, monthlySalary);
this.annualSales = annualSales;
} // end Salesman constructor method
#Override // takes advantage from compiler checking
// Computes commission and annual salary
public int annualSalary() {
int commission = annualSales * 3 / 100;
// if commission is greater than 25000, then set commission to 25000
if (commission > 25000) {
commission = 25000;
} // emd comission if
return (monthlySalary * 12 + commission);
} // end annualSalary method
#Override // takes advantage from compiler checking
// Displays output details as String
public String toString(){
return "Employee Name: " + employeeName +
" Salary: $" + monthlySalary;
} // end toString method
} // end Salesman class
/**
* This class contains the current stock price and extends employee class
*/
// Executive subclass, extends Employee class
class Executive extends Employee {
// Variable declaration
int currentStockPrice = 0;
// Executive constructor
public Executive(String employeeName,
int monthlySalary, int currentStockPrice) {
super(employeeName, monthlySalary);
this.currentStockPrice = currentStockPrice;
} // end Executive constructor method
#Override // takes advantage from compiler checking
// Computes commission and annual salary
public int annualSalary() {
int executiveBonus = 0;
// Adds executive bonus if stock is greater than 100
if(currentStockPrice > 100) {
executiveBonus = 20000;
} // end executiveBonus if
return (monthlySalary * 12 + executiveBonus);
} // end annualSalary method
#Override // takes advantage from compiler checking
// Displays output details as String
public String toString() {
return "Employee Name: " + employeeName +
" Salary: $" + monthlySalary;
} // end toString method
} // end Executive class
/**
* This class computes salary based on input file and reports results
*/
public class ComputeEmployeeSalary {
// Main method
public static void main(String[] args) throws IOException {
// Import text file and compute salary increase
try {
// Create a File instance
java.io.File file = new java.io.File("employees.txt");
// Create Scanner object
Scanner input = new Scanner(file);
// Create arrays for 2014 and 2015
Employee year2014[] = new Employee[20];
Employee year2015[] = new Employee[20];
// Create indexes for 2014 and 2015 arrays
int indexYear2014 = 0, indexYear2015 = 0;
// Read data from a file
while (input.hasNext()) {
String year = input.next();
String employeeTitle = input.next();
String employeeName = input.next();
int monthlySalary = input.nextInt();
// Action if employee is a regular employee.
if (employeeTitle.equalsIgnoreCase("Employee")) {
Employee regularEmployee = new Employee(employeeName,
monthlySalary);
if (year == "2014") {
year2014[indexYear2014++] = regularEmployee;
} // end 2014 if
if (year == "2015") {
year2015[indexYear2015++] = regularEmployee;
} // end 2015 if
} // end Employee if
// Action if employee is a salesman.
if (employeeTitle.equalsIgnoreCase("Salesman")){
int annualSales = input.nextInt();
Salesman salesEmployee = new Salesman(employeeName,
monthlySalary, annualSales);
if (year == "2014") {
year2014[indexYear2014++] = salesEmployee;
} // end 2014 if
if (year == "2015") {
year2015[indexYear2015++] = salesEmployee;
} // end 2015 if
} // end Salesman if
// Action if employee is an executive.
if (employeeTitle.equalsIgnoreCase("Executive")) {
int currentStockPrice = input.nextInt();
Executive executiveEmployee = new Executive(employeeName,
monthlySalary, currentStockPrice);
if (year == "2014") {
year2014[indexYear2014++] = executiveEmployee;
} // end 2014 if
if (year == "2015") {
year2015[indexYear2015++] = executiveEmployee;
} // end 2015 if
} // end Executive if
} // end While
// Generate Report for 2014
int totalSalary = 0;
System.out.println("===== Salary Report for 2014 =====");
for (int i = 0; i < indexYear2014; i++) {
System.out.print(year2014[i]);
System.out.println(" Annual Salary: " +
year2014[i].annualSalary());
} // end annualSalary 2014 for
for (int i = 0; i < indexYear2014; i++) {
totalSalary+= year2014[i].annualSalary();
} // end totalSalary 2014 for
System.out.println("\nAverage Salary for 2014: " +
(totalSalary / indexYear2014));
// Generate Report for 2015
System.out.println("\n===== Salary Report for 2015 =====");
for (int i = 0; i < indexYear2015; i++) {
System.out.print(year2015[i]);
System.out.println(" Annual Salary: " +
year2015[i].annualSalary());
} // end annualSalary 2015 for
for (int i = 0; i < indexYear2015; i++) {
totalSalary+= year2015[i].annualSalary();
} // end totalSalary 2015 for
System.out.println("\nAverage Salary for 2015: " +
(totalSalary / indexYear2015));
// Close input file
input.close();
} // end try
catch (IOException i) {
System.out.println("Error: File Not Found, error code: " + i);
} // end catch
} // end main method
} // end ComputeEmployeeSalary class
Any help would be greatly appreciated.
The reason it works when you comment out those 2 lines is that they cause a divide by zero error. Both indexYear2014 and indexYear2015 are 0.
The reason for this is the way you're comparing Strings:
year == "2015" should be year.equals("2015")
i have 2 java programs , the first one takes all information about the employee(id , name , department etc)from the user and prints it , the second program lets the user choose how many number of employees are there then it takes the values like(employ id, name etc), this program uses an array to store the values , it should print all values of different employees , but when i run the program the second set of values overrides the first set of values and prints the second set of values twice , im a beginner so plse help
This is the first program
import java.util.Scanner;
public class payroll2
{
public static void main(String args[])
{
payroll2 payroll = new payroll2();
payroll.SetPayrollDetail();
payroll.SetBonus();
payroll.SetCommission();
payroll.SetNssf();
payroll.SetNetSalary();
payroll.GetPayroll();
}
Scanner myScanner=new Scanner(System.in);
int empID;
String empName;
String empDept;
String designation;
int basicSalary;
double bonus;
double commission;
double nssf;
double netSalary;
public void SetPayrollDetail()
{
System.out.println("Enter ID: ");
empID = myScanner.nextInt();
System.out.println("Enter Name: ");
empName = myScanner.next();
System.out.println("Enter Department (Marketing or Other): ");
empDept = myScanner.next();
System.out.println("Enter Designation (Manager, Executive or Other): ");
designation = myScanner.next();
System.out.println("Enter Basic Salary: ");
basicSalary = myScanner.nextInt();
}
public void SetBonus()
{
if(basicSalary < 1500){
bonus = 0.0;
}
else if(basicSalary>=1500 && basicSalary<3000){
bonus = basicSalary * (12.0/100.0);
}
else if(basicSalary>=3000 && basicSalary<5000){
bonus = basicSalary * (15.0/100.0);
}
else{
bonus = basicSalary * (25.0/100.0);
}
}
public void SetCommission()
{
if( empDept.equalsIgnoreCase("other") ){
commission = 0.0;
}
else if( empDept.equalsIgnoreCase("marketing") && designation.equalsIgnoreCase("manager") ){
commission = basicSalary * (30.0/100.0);
}
else if( empDept.equalsIgnoreCase("marketing") && designation.equalsIgnoreCase("executive") ){
commission = basicSalary * (15.0/100.0);
}
else if( empDept.equalsIgnoreCase("marketing") && designation.equalsIgnoreCase("other") ){
commission = basicSalary * (10.0/100.0);
}
else{
commission = 0.0;
}
}
public void SetNssf()
{
if(basicSalary < 1500){
nssf = basicSalary * (5.0/100.0);
}
else if(basicSalary>=1500 && basicSalary<3000){
nssf = basicSalary * (8.0/100.0);
}
else if(basicSalary>=3000 && basicSalary<5000){
nssf = basicSalary * (12.0/100.0);
}
else if(basicSalary>=5000 && basicSalary<7000){
nssf = basicSalary * (15.0/100.0);
}
else if(basicSalary>=7000 && basicSalary<10000){
nssf = basicSalary * (20.0/100.0);
}
else{
nssf = basicSalary * (25.0/100.0);
}
}
public void SetNetSalary()
{
netSalary = ( basicSalary + commission + bonus ) - nssf;
}
public void GetPayroll()
{
System.out.println("\n\nPayroll Details \n _____________________");
System.out.println("ID:\t\t" + empID);
System.out.println("name:\t\t" + empName);
System.out.println("Bonus:\t\t" + bonus);
System.out.println("Commission:\t"+commission);
System.out.println("NSSF:\t\t"+nssf);
System.out.println("Net Salary:\t"+netSalary);
}
}
This is the second program
import java.util.Scanner;
public class display{
public static void main(String[]args){
Scanner scan = new Scanner(System.in);
int counter;
int limit;
System.out.println("How many employess do u want to enter?\n Enter here: ");
limit = scan.nextInt();
int[] a = new int[limit];
payroll2 payroll = new payroll2();
for(counter=1; counter<=limit; counter++){
System.out.println("\n\nEnter employee "+counter+" details\n");
payroll.SetPayrollDetail();
payroll.SetBonus();
payroll.SetCommission();
payroll.SetNssf();
payroll.SetNetSalary();
}
for(counter=1; counter<=limit; counter++){
payroll.GetPayroll();
//System.out.println(a);
}
}
}
This is the area of code that there's a problem in:
for(counter=1; counter<=limit; counter++){
System.out.println("\n\nEnter employee "+counter+" details\n");
payroll.SetPayrollDetail();
payroll.SetBonus();
payroll.SetCommission();
payroll.SetNssf();
payroll.SetNetSalary();
}
for(counter=1; counter<=limit; counter++){
payroll.GetPayroll();
//System.out.println(a);
}
If you think about what this does. So a payroll2 object is a single entity. When you enter them in the first for loop, you create one person. Then if you loop through that a second or third time, you overwrite that person, since you are saving to the same variable.
Then when you loop through the second loop, you are printing the payroll entity, which holds the value of the last entered person. Since the other data gets overwritten, its no surprise that you get the same guy printed limit times.
What you will want to do is build an array of payroll entities. This code accomplishes this:
payroll2[] PayrollList = new payroll2[limit]; // establish the array with correct size
for(counter=0; counter<=limit - 1; counter++){ // bounds of the array are 0 to limit - 1
payroll = new payroll(); // hard reset of the variable to make sure data is cleared
System.out.println("\n\nEnter employee "+counter+" details\n");
payroll.SetPayrollDetail();
payroll.SetBonus();
payroll.SetCommission();
payroll.SetNssf();
payroll.SetNetSalary();
PayrollList[counter] = payroll; // adds it to the array at position counter
}
for(counter=0; counter<=limit - 1; counter++){
PayrollList[counter].GetPayroll(); // gets the payroll2 object from the array and calls its function
}
DISCLAIMER: I have not run the modified code through a compiler, so it may not be 100% syntax correct, but it is very close.
I have my code working right, the only problem is that my output isn't correct because I can't find the right place to set the array of numbers back to zero. The basis of the programs is to take in data that contains names with corresponding grades. My output should follow this criteria:
Alice [87, 99, 96, 99, 86, 96, 77, 95, 70, 88]
Name: Alice
Length: 10
Average: 89.30
Median: 91.5
Maximum: 99
Mininum: 70
I get the first person's results correct, however, the ones that follow are incorrect because they contain all of the values being read in for every person. So, the next person will have "Alice's" grades plus their own when my code performs operations on the array for that person. I have two programs, the first is the main program that reads the data in and calls the methods to print and operate. The second is the class with all the methods that perform the operations.
This is the main program:
public class Lab2 {
public static void main(String[] args) {
Scanner in = null; //initialize scanner
ArrayList<Integer> gradeList = new ArrayList<Integer>(); //initialize gradeList
//grab data from data.txt
try {
in = new Scanner(new File("data.txt"));
} catch (FileNotFoundException exception) {
System.err.println("failed to open data.txt");
System.exit(1);
}
//while loop to grab tokens from data
while (in.hasNext()) {
String studentName = in.next(); //name is the first token
while (in.hasNextInt()) { //while loop to grab all integer tokens after name
int grade = in.nextInt(); //grade is next integer token
gradeList.add(grade); //adding every grade to gradeList
}
//grab all grades in gradeList and put them in an array to work with
int[] sgrades = new int[gradeList.size()];
for (int index = 0; index < gradeList.size(); index++) {
sgrades[index] = gradeList.get(index); //grade in gradeList put into grades array
}
Grades myGrade = new Grades(studentName,sgrades);
testGrades(myGrade);
sgrades = null;
}
}
public static void testGrades(Grades grades) {
System.out.println(grades.toString());
System.out.printf("\tName: %s\n", grades.getName());
System.out.printf("\tLength: %d\n", grades.length());
System.out.printf("\tAverage: %.2f\n", grades.average());
System.out.printf("\tMedian: %.1f\n", grades.median());
System.out.printf("\tMaximum: %d\n", grades.maximum());
System.out.printf("\tMininum: %d\n", grades.minimum());
grades = null;
}
}
I've tried adding place to erase the values of the array for the next person by setting it to null. I've had no luck with this.
This is the next program, which contains the methods.
public class Grades {
private String studentName; // name of course this GradeBook represents
private int[] grades; // array of student grades
/**
* #param studentName The name of the student.
* #param grades The grades for the student.
*/
public Grades(String name, int[] sgrades) {
studentName = name; // initialize courseName
grades = sgrades; // store grades
} // end two-argument GradeBook constructor
/**
* Method to convert array to a string and print.
*
* #return The name of the student with array of grades.
*/
public String toString() {
return (String) studentName + " " + Arrays.toString(grades);
}
/**
* One-argument constructor initializes studentName.
* The grades array is null.
*
* #param name The name of the student.
*/
public Grades(String name) {
studentName = name; // initialize courseName
} // end one-argument Grades constructor
/**
* Method to set the student name.
*
* #return The name of the student.
*/
public String getName() {
return studentName;
} // end method getCourseName
/**
* Method to set the length of the amount of grades.
*
* #return Number of grades for student.
*/
public int length() {
return grades.length;
}
/**
* Determine average grade for grades.
*
* #return the average of the grades.
*/
public double average() {
double total = 0; // initialize total
double average = 0.0;
// sum grades for one student, while loop
int index = 0;
while (index < grades.length) {
int grade = grades[index]; // get grade at index
total += grade;
index++; // need to increment
}
average = total / grades.length;
// return average of grades
return (double) average;
} // end method getAverage
/**
* Determine median grade for grades.
*
* #return the median of the grades.
*/
public double median() {
Arrays.sort(grades); //sort grades array
double median = 0.0;
if (grades.length%2 == 0) //checks to see if amount of grades is even/odd
//this is median if list of grades is even
median = ((double)grades[grades.length/2-1] + (double)grades[grades.length/2])/2;
else
//this is median if list of grades is odd
median = (double) grades[grades.length/2];
return (double) median;
}
/**
* Find minimum grade.
*
* #return the minimum grade.
*/
public int minimum() {
int lowGrade = grades[0]; // assume grades[0] is smallest
// loop through grades array, for loop
for (int index = 0; index < grades.length; index++) {
int grade = grades[index]; // get grade at index
// if grade lower than lowGrade, assign it to lowGrade
if (grade < lowGrade)
lowGrade = grade; // new lowest grade
} // end for
return lowGrade; // return lowest grade
} // end method getMinimum
/**
* Find maximum grade.
*
* #return the maximum grade.
*/
public int maximum() {
int highGrade = grades[0]; // assume grades[0] is largest
// loop through grades array, for-each loop
for (int grade : grades) {
// if grade greater than highGrade, assign it to highGrade
if (grade > highGrade)
highGrade = grade; // new highest grade
} // end for
return highGrade; // return highest grade
} // end method getMaximum
}
My main question is, how can I "refresh" the array for every new student that I read in?
You're looking for gradeList.clear(). But why are you copying everything from gradeList to sgrades? Seems kind of redundant.