I made a class with an ArrayList that holds "Student" Objects and I have a toString method that prints the Students test scores,name,etc. But I keep getting "java.lang.IndexOutOfBoundsException: Index: 0, Size: 0" here is my code, if you need to see any more code just comment
public class School2 {
ArrayList <Student2> studentArray;// array of Student's
/**
* Constructor for School, creates an array of for ten Student's.
*/
public School2() {
final int NUMSTUDENTS = 10;
studentArray = new ArrayList <Student2> (NUMSTUDENTS);
}// end constructor
/**
* Method adds a student 'newStudent' to the array of Student's.
* #param newStudent - Student to be added
*/
public void add(Student2 newStudent) {
studentArray.add(newStudent);
}// end method
/**
* Method adds a Student whose name and test scores are passed in parameter.
* #param name - name of newly added Student
* #param tests - array of test scores belonging to newly added Student
*/
public void add(String name, ArrayList <Integer> testScores) {
Student2 studentAdded = new Student2(name, testScores);
studentArray.add(studentAdded);
}// end method
/**
* Method adds a Student whose name is passed in parameter.
* #param name - name of newly added Student
*/
public void add(String name) {
Student2 studentAdded = new Student2(name);
studentArray.add(studentAdded);
}// end method
/**
* Method adds a Student whose name is an empty String and test scores are 0.
*/
public void add() {
Student2 studentAdded = new Student2();
studentArray.add(studentAdded);
}// end method
/**
* Method removes all Student object 's' from array of Student's
* #param s - Student to be removed from array of Student's
*/
public void remove(Student2 s) {
for (int i = 0; i < studentArray.size(); i++) {
if (studentArray.get(i) == s) {
studentArray.remove(i);
}// end if statement
}// end for loop
}// end method
/**
* Method removes the Student whose index is passed in the parameter
* #param index - index at which the Student is located
*/
public void remove(int index) {
studentArray.remove(index);
}// end method
/**
* Method removes the Student whose name is passed in the parameter
* #param name - name of Student to be removed
*/
public void remove(String name) {
for (int i = 0; i < studentArray.size(); i++) {
if (studentArray.get(i).getName() == name) {
studentArray.remove(i);
}// end if statement
}// end for loop
}// end method
/**
* Method replaces the Student whose index is passed in the parameter with a
* different Student object 'newStudent'
* #param index - index of Student to be replaced
* #param newStudent - Student object to replace other Student
*/
public void replace(int index, Student2 newStudent) {
studentArray.set(index, newStudent);
}// end method
/**
* Method returns the student with the highest test score
* #return - Student with the highest test score
*/
public Student2 getHighScore() {
int index = 0;
int highScore = 0;
for (int i = 0; i < studentArray.size(); i++) {
if (studentArray.get(i).getHighScore() > highScore) {
index = i;
highScore = studentArray.get(i).getHighScore();
}// end if statement
}// end for loop
return studentArray.get(index);
}// end method
/**
* Method returns the class average
*
* #return - class average of test scores
*/
public int getClassAverage() {
int totalScores = 0;
int numTests = 0;
for (int i = 0; i < studentArray.size(); i++) {
for (int x = 1; x <= 3; x++) {
totalScores += studentArray.get(i).getScore(x);
}
numTests += 3;
}// end for loop
return (totalScores / numTests);
}// end method
/**
* Getter method returns a Student whose index is passed in the parameter
* #param index - index of Student object
* #return - Student object
*/
public Student2 getStudent(int index) {
return (studentArray.get(index));
}// end method
/**
* Getter method returns a Student whose name is passed in the parameter
* #param name - name of Student
* #return - Student object
*/
public Student2 getStudent(String name) {
int index = 0;
for (int i = 0; i < studentArray.size(); i++) {
if (studentArray.get(i).getName() == name) {
index = i;
}// end if statement
}// end for loop
return (studentArray.get(index));
}// end method
/**
* Method returns a string containing the names and test scores of all
* students, the class average, and the highest score and the name of the
* student with the highest score.
*/
public String toString() {
String school = "";
for (int i = 0; i < studentArray.size(); i++) {
school += "Name: " + studentArray.get(i).getName() + ":";
//nested for loop gets all 3 tests and concatenates the scores to 'school' string
for (int test = 1; test <= 3; test++) {
school += " test " + test + ": ";
school += studentArray.get(i).getScore(test);
}// end nested for loop
school += " Average: " + studentArray.get(i).getAverage();
school += " High Score: " + studentArray.get(i).getHighScore()
+ "\n";
}// end nested for loop
school += "Class Average: " + getClassAverage() + "\n";
school += "Highest score\n";
school += getHighScore() + "\n";
return school;
}// end method
}//end class
public class Student2
{
String studentName;// name of Student
ArrayList <Integer> studentScores;// test scores of student
final int NUMTESTS = 3;//Student has 3 different test scores
/**
* Constructor for Student2 class, sets name of student to an empty String
* and test scores to 0.
*/
public Student2(){
studentName = "";
studentScores = new ArrayList <Integer> (NUMTESTS);
}//end constructor
/**
* Constructor for Student2 class, sets name to String passed in parameter
* and test scores to 0.
* #param name - name of student
*/
public Student2(String name){
studentName = name;
studentScores = new ArrayList <Integer> (NUMTESTS);
}//end constructor
/**
* Constructor for Student2 class, sets name and test scores to the String
* and array passed in the parameter
*/
public Student2(String name, ArrayList<Integer> testScores){
studentName = name;
studentScores = testScores;
}//end constructor
/**
* Constructor for Student2 class, sets the name and test scores to Student2 's'.
* #param s - Student object
*/
public Student2(Student2 s){
studentName = s.getName();
studentScores = new ArrayList <Integer> (NUMTESTS);
for(int i = 0; i < studentScores.size(); i++){
studentScores.add(s.getScore(i + 1));
}//end for loop
}//end constructor
/**
* Sets name of Student to String passed in parameter
* #param name - name of Student
*/
public void setName(String name) {
studentName = name;
}// end method
/**
* Getter method for Student's name
* #return studentName - name of Student
*/
public String getName() {
return studentName;
}// end method
/**
* Setter method which re-intializes a Student's test score at a given index
* whose values are passed in the parameter
* #param whichTest - test to be set
* #param testScore - value of test to be set
*/
public void setScore(int whichTest, int testScore) {
if (whichTest >= 3) {
studentScores.set(2, testScore);
} else {
studentScores.set((whichTest - 1), testScore);
}
}// end method
/**
* Setter method, re-intializes all test scores to the array passed in the
* parameter
* #param testScores - array of test scores
*/
public void setScore(int[] testScores) {
for(int i = 0; i < testScores.length; i++){
studentScores.set(i, testScores[i]);
}//end for loop
}// end method
/**
* Getter method to get a Student's test score
* #param whichTest - test number
* #return score - score of the particular test number
*/
public int getScore(int whichTest) {
int score = 0;
if (whichTest >= 3) {
score = studentScores.get(2);
} else {
score = studentScores.get((whichTest - 1));
}
return score;
}// end method
/**
* Method calculates the average of the Student's test scores
* #return - average of Student's test scores
*/
public int getAverage() {
int total = 0;
int numTests = 0;
for (int i = 0; i < studentScores.size(); i++) {
total += studentScores.get(i);
numTests++;
}
return (total / numTests);
}// end method
/**
* Method to get the Student's highest test score
* #return highScore - Student's highest test score
*/
public int getHighScore() {
int highScore = 0;
for (int i = 0; i < studentScores.size(); i++) {
if (studentScores.get(i) > highScore) {
highScore = studentScores.get(i);
}//end if statement
}//end for loop
return highScore;
}// end method
/**
* Method returns a String containing the Student's name, test scores,
* average score and high score.
*/
public String toString() {
String student = "Name: " + getName() + ":";
for(int test = 1; test <= studentScores.size(); test++){
student += " test " + test + ": " + getScore(test);
}
student += " Average: " + getAverage();
student += " High Score: " + getHighScore();
return student;
}// end method
}//end class
Driver Code:
School2 mySchool = new School2();
ArrayList<Student2> studentArr = mySchool.studentArray;
Student2 s = new Student2("Olive Oyl", randomScores());
mySchool.add(s);
mySchool.add("Popeye", randomScores());
mySchool.add("Bluto");
mySchool.add();
System.out.println(mySchool);
Exception message:
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
at java.util.ArrayList.rangeCheck(Unknown Source)
at java.util.ArrayList.get(Unknown Source)
at Student2.getScore(Student2.java:107)
at School2.toString(School2.java:176)
at java.lang.String.valueOf(Unknown Source)
at java.io.PrintStream.println(Unknown Source)
at Driver.main(Driver.java:25)`
for (int test = 1; test <= 3; test++)
Should this be
for (int test = 0; test < 3; test++)
Probably you have an error not at this loop, but in Student class.
First try this code
String school = "";
for (int i = 0; i < studentArray.size(); i++) {
school += "Name: " + studentArray.get(i).getName() + ":\n";
}
return school;
Then try change your inner loop to
for (int test = 1; test <= 3; test++) {
school += " test " + test + ": ";
school += studentArray.get(i-1).getScore(test);
}// end nested for loop
Because most likely error is here
Added.
Error is here
public Student2(){
studentName = "";
studentScores = new ArrayList <Integer> (NUMTESTS);
}
because
studentScores = new ArrayList <Integer> (NUMTESTS);
NOT fill studentScores with 4 empty integer.
After this line studentScores.size() return 0 insted of 4
There are some mistakes in your code.
Please update your code of getClassAverage() method from School2 class to
public int getClassAverage() {
int totalScores = 0;
int numTests = 0;
for (int i = 0; i < studentArray.size(); i++) {
for (int x = 1; x <= studentArray.get(i).studentScores.size(); x++) {
totalScores += studentArray.get(i).getScore(x);
}
numTests += 3;
}// end for loop
return (totalScores / numTests);
}// end method
And also toString() method of School2 class to
public String toString() {
String school = "";
for (int i = 0; i < studentArray.size(); i++) {
school += "Name: " + studentArray.get(i).getName() + ":";
//nested for loop gets all 3 tests and concatenates the scores to 'school' string
for (int test = 1; test <= studentArray.get(i).studentScores.size(); test++) {
school += " test " + test + ": ";
school += studentArray.get(i).getScore(test);
}// end nested for loop
school += " Average: " + studentArray.get(i).getAverage();
school += " High Score: " + studentArray.get(i).getHighScore()
+ "\n";
}// end nested for loop
school += "Class Average: " + getClassAverage() + "\n";
school += "Highest score\n";
school += getHighScore() + "\n";
return school;
}// end method
Also make changes in getAverage() method of Student2 class as below:
public int getAverage() {
int total = 0;
int numTests = 0;
for (int i = 0; i < studentScores.size(); i++) {
total += studentScores.get(i);
numTests++;
}
if (numTests == 0) {
return 0;
} else {
return (total / numTests);
}
}// end method
I hope you will get the point from where actually the exception is throwing, cheers.
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]
Main.java
import java.util.*;
public class Main{
static Student[] students = new Student[10];//creates an array of 10 students to be entered
public static int inputThreshold(){
Scanner scan = new Scanner(System.in);
System.out.println("Please enter the Threshold: \n");
int threshold = scan.nextInt();
return Threshold();
}
public static Student inputStudent(){
Scanner scan = new Scanner(System.in);
System.out.println("Enter students surname: \n");//instructs the user to enter a surname
String name = scan.nextLine();//allows the user to input sdtudents surname
System.out.println("Enter student score between 0 and 30: \n");
int score = scan.nextInt();//allows the user to input students score
return new Student(name, score);
}
public static void printStudent(Student student){
int percentage = student.getScore()*10/3;//retrieves the percentage of the score submitted out of 30
System.out.println("Surname: " + student.getName() + " Score: " + student.getScore() + " Percentage: " + percentage + "%");
//prints out the surname, score and percentage achieved by the student
}
public static void printThreshold(int threshold){
int percentage = student.getScore()*10/3;//retrieves the percentage of the score submitted out of 30
if (percentage < threshold){
System.out.println("Surname: " + student.getName() + " Score: " + student.getScore() + " Percentage: " + percentage + "%");
//prints out the surname, score and percentage achieved by the student
}
}
public static Student getWinner(Student[] student){
Student x = student[0];
for(int i = 1; i < 10; i++){
if(student[i].getScore() > x.getScore()){
x = student[i];
}
}
return x;
}
public static void main(String[] args){
for (int i = 0; i = 1; i++){
threshold = inputThreshold;
}
for (int i = 0; i < 10; i++){
students[i] = inputStudent();
}
for(int i = 0; i < 10; i++){
printStudent(students[i]);
}
for(int i= 0; i < 1; i++){
printThreshold(students[i]);
}
Student winrar = getWinner(students);//retrieves the winner from getWinner into a variable
System.out.println("AND WE HAVE OUR WINNER! \n" + "Name: " + winrar.getName() + " Score: " + winrar.getScore());
//prints out the highest scoring students surname, with their score
}
}
Student.java
public class Student{
private String name;//sets name to characters
private int score;//sets score to numbers
private int threshold;//sets the threshold of the score
private int max = 30;//sets max score to 30
public Student(String name, int score){
this.name = name;
if (score <= max && score >= 0) //if the score is equal to 30 or less than 0
this.score = score;//the score can be stored
else{
System.out.println("This number is too big ");//if it is larger than 30 it cannot be stored and shows errors message
System.exit(1);//this will end the program
}
}
public String getName(){
return name;
}
public int getScore(){
return score;
}
public int getThreshold(){
return threshold;
}
public void setScore(int s){
this.score = s;
}
public void setName(String n){
this.name = n;
}
public void setThreshold(int t){
this.threshold = t;
}
}
Is returns Cannot Find Symbol - method Threshold()
I'm not sure what to refer to or how to call the method to get it to run correctly. Brief: 10 users, 10 scores. There's a threshold to be achieved by each entrant. The program outputs their names, scores achieved and the percentage of their score. But it should also announce the overall winner.
Not sure here
return Threshold();
should be
return threshold;
change Threshold() to threshold.
I strongly advice you to read this article before writing another program
Objects, Instance Methods, and Instance Variables
public static int inputThreshold(){
Scanner scan = new Scanner(System.in);
System.out.println("Please enter the Threshold: \n");
int threshold = scan.nextInt();
return Threshold();
}
public static void main(String[] args){
for (int i = 0; i = 1; i++){
threshold = inputThreshold;
}
...rest of code in main
}
threshold is a local variable defined in inputStudent(), you can't access it in main() .Also return Threshold();, there is no Threshold() method defined in the code you've provided
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.
OK, now that I have change the public static String to public static int the last function does not print out.
Thank you all for you're help.
Here is the full program. The last function does not seem to print.
import java.lang.String;
import java.util.Scanner;
public class stringFuncts{
/**
* #param <String> <str> <Takes in a String and reverses it.>
* #return <rev> <returns the reversed string>
*/
public static String reverseString (String str){
String rev = "";
int length = str.length();
for ( int i = length - 1 ; i >= 0 ; i-- ){
rev = rev + str.charAt(i);
}
return rev;
}
/**
* #param <int> <n> <It will sum up the odds of a set number>
* #return <results> <Will print out the total of the odds values>
*/
public static int sumOfOdds (int n){
int results = 0;
for(int i = 1; i <= n*2; i += 2){
results = results + i;
}
return results;
}
/**
* #param <int> <blanks> <Will count the amount of whitespace in the phrase>
* #return <numBlanks> <Will return the amount of whitespace found in the String>
*/
public static int numberOfBlanks(String blanks){
int numBlanks = 0;
for(int i = 0; i < blanks.length(); i++) {
if(Character.isWhitespace(blanks.charAt(i)))
numBlanks++;
}
return numBlanks;
}
public static void main(String [] args){
Scanner input = new Scanner(System.in);
String str;
int n = 0;
String blanks;
System.out.println("Enter a string to reverse");
str = input.nextLine();
System.out.println("The reverse output is: " + reverseString(str));
System.out.println("");
System.out.println("Enter a value to sum the odds");
n = input.nextInt();
System.out.println("The sum of the odds " + sumOfOdds(n));
System.out.println("");
System.out.println("Enter a string to find the amount of blanks");
blanks = input.nextLine();
System.out.print("The number od blanks in the string is: " + numberOfBlanks(blanks));
}
}
In your numberOfBlanks() return type is of String data type
change it to int data type
Your function is declared as public static String. You're trying to return a number, so the correct declaration would be public static int.
import java.lang.String;
import java.util.Scanner;
public class stringFuncts{
/**
* #param <String> <str> <Takes in a String and reverses it.>
* #return <rev> <returns the reversed string>
*/
public static String reverseString (String str){
String rev = "";
int length = str.length();
for ( int i = length - 1 ; i >= 0 ; i-- ){
rev = rev + str.charAt(i);
}
return rev;
}
/**
* #param <int> <n> <It will sum up the odds of a set number>
* #return <results> <Will print out the total of the odds values>
*/
public static int sumOfOdds (int n){
int results = 0;
for(int i = 1; i <= n*2; i += 2){
results = results + i;
}
return results;
}
/**
* #param <int> <blanks> <Will count the amount of whitespace in the phrase>
* #return <numBlanks> <Will return the amount of whitespace found in the String>
*/
public static int numberOfBlanks(String blanks){
int numBlanks = 0;
for(int i = 0; i < blanks.length(); i++) {
if(Character.isWhitespace(blanks.charAt(i)))
numBlanks++;
}
return numBlanks;
}
public static void main(String [] args){
Scanner input = new Scanner(System.in);
String str;
int n = 0;
String blanks;
System.out.println("Enter a string to reverse");
str = input.nextLine();
System.out.println("The reverse output is: " + reverseString(str));
System.out.println("");
System.out.println("Enter a value to sum the odds");
n = input.nextInt();
System.out.println("The sum of the odds " + sumOfOdds(n));
System.out.println("");
input.nextLine();
System.out.println("Enter a string to find the amount of blanks");
blanks = input.nextLine();
System.out.print("The number od blanks in the string is: " + numberOfBlanks(blanks));
}
}
Output:
Enter a string to reverse
this
The reverse output is: siht
Enter a value to sum the odds
3
The sum of the odds 9
Enter a string to find the amount of blanks
this is spartan!
The number od blanks in the string is: 2
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.