Baseball Menu Insertion sort part - java

I'm trying to use insertion sort to sort for the batting average of the players. I get an error message "The method get(int) in the type java.util.ArrayList is not applicable for the arguments (double)" on the lines of S.get(outer) and S.get(inner - 1)
What am I doing wrong?
How can I fix this?
import java.util.*;
import java.io.*;
class menu {
public static void main (String [] arg) throws IOException
{
PlayerRip.PlayerInfo obj5 = new PlayerRip.PlayerInfo();
ArrayList<Player> obj6 = new ArrayList<Player>();
MainMenu(obj5, obj6);
}
public static void MainMenu(PlayerRip P, ArrayList<Player> S) throws IOException
{
Scanner keyboard = new Scanner(System.in);
int response = 0;
int response2 = 0;
ArrayList<Player> obj1 = new ArrayList<Player>();
obj1.add(new Player("Agostini", "Aldo", "Pitcher", 170, 20, 72, 12, 6, 1, 1, 0));
do
{
System.out.println("1. Open A file:");
System.out.println("7. Exit the program");
response = keyboard.nextInt();
switch (response)
{
case 1:
{
openFile(obj1);
do
{
System.out.println("2. Display all players");
System.out.println("3. Enter player's Height");
System.out.println("4. Sort all players alphabetically by Surname");
System.out.println("5. Sort all players by batting average");
System.out.println("6. Delete a player by selecting the player's surname from a list");
System.out.println("7. Add a player to the stats");
System.out.println("8. Save stats to a file");
System.out.println("9. Exit the program");
response2 = keyboard.nextInt();
switch (response2)
{
case 2:
{
displayInfo(obj1);
break;
}
case 3:
{
changeHeight(obj1);
break;
}
case 4:
{
BubbleSort(obj1);
break;
}
case 5:
{
break;
}
case 6:
{
deletePlayerInfo(obj1);
break;
}
case 7:
{
addPlayerInfo(obj1);
break;
}
case 8:
{
saveFile(obj1);
break;
}
case 9:
{
System.exit(0);
break;
}
}
} while (response2 != 9);
break;
}
case 7:
{
System.exit(0);
break;
}
}
} while (response != 1 || response != 7); // End of switch statement
}
public static void displayInfo(ArrayList<Player> S) {
System.out.printf("%10s %10s %10s \t %4s %4s \t %4s \t %4s %4s \t %4s %4s %4s \n", "Surname", "GivenName", "Postition", "Height(cm)", "Hits", "AtBats", "Singles", "Doubles", "Triples", "HomeRuns", "Batting Average");
for (int index = 0; index < S.size(); index++)
S.get(index).displayInfo();
}
public static void openFile(ArrayList<Player> S) throws IOException // This method allows the oepning of files into the program
{
Scanner userInput = new Scanner(System.in);
String fileName;
S.removeAll(S); // Empties the list readies it for a new oned
System.out.println("Enter a file name to open: ");
fileName = userInput.next().trim();
File file = new File(fileName);
if (file.exists()) // Checks whether or not the file exists in the directory
{
Scanner fileInput = new Scanner(file);
while (fileInput.hasNext())
{
S.add(new Player(fileInput.next(), fileInput.next(), fileInput.next(), fileInput.nextInt(), fileInput.nextInt(), fileInput.nextInt(), fileInput.nextInt(), fileInput.nextInt(), fileInput.nextInt(), fileInput.nextInt(), fileInput.nextDouble())); // If it exists it adds the token values into the respective lists
}
fileInput.close(); // Closes further file input
}
else // Error message incase the file-name is not valid
System.out.println("FILE NOT FOUND");
}
public static void saveFile(ArrayList<Player> S) throws IOException // This method allows for the saving of values to an external file
{
Scanner inputInfo = new Scanner(System.in);
String fileName;
System.out.println("Enter a file name to save the info with:");
fileName = inputInfo.next().trim();
File file = new File(fileName);
PrintStream writeFile = new PrintStream(file);
for (int i = 0; i < S.size(); i++) // Gathers all values and prints them to the file in their respective format
{
writeFile.print(S.get(i).getName() + " ");
writeFile.print(S.get(i).getName2() + " ");
writeFile.print(S.get(i).getPosition() + " ");
for (int j = 0; j < 7; j++)
writeFile.print(S.get(i).getMark(j) + " ");
for (int j = 0; j < 1; j++)
writeFile.print(S.get(i).getBatAvg(j));
writeFile.println(" ");
}
writeFile.close(); // Stops any further writing to the file
}
public static void deletePlayerInfo(ArrayList<Player> S) // THis method allows the user to delete any player within the list
{
int deleteIt = 0;
Scanner keyboard = new Scanner(System.in);
System.out.println("Please select the number of the player to be deleted: ");
for (int i = 0; i < S.size(); i++) // Displays only the first/surNames of the players
{
System.out.print(i + ". " + S.get(i).getName());
System.out.println(" ");
}
deleteIt = keyboard.nextInt();
S.remove(deleteIt);
}
public static void addPlayerInfo(ArrayList<Player> S) // This method allows the user to add a new player to the list
{
String firstName = "";
String surName = "";
String posName = "";
int heightVal = 0;
int hitsVal = 0;
int atBatsVal = 0;
int singVal = 0;
int doubVal = 0;
int tripVal = 0;
int homeVal = 0;
Scanner keyboard = new Scanner(System.in); // Various user input
System.out.println("Enter the surname and name of the new player: ");
System.out.println("Surname: ");
surName = keyboard.nextLine();
System.out.println("Name: ");
firstName = keyboard.nextLine();
System.out.println("Enter the position of the new player: ");
System.out.println("Position: ");
posName = keyboard.nextLine();
System.out.println("Enter the height of the new player: ");
heightVal = keyboard.nextInt();
System.out.println("Enter the batting statistics: ");
System.out.println("Hits: ");
hitsVal = keyboard.nextInt();
System.out.println("AtBats: ");
atBatsVal = keyboard.nextInt();
System.out.println("Singles: ");
singVal = keyboard.nextInt();
System.out.println("Doubles: ");
doubVal = keyboard.nextInt();
System.out.println("Triples: ");
tripVal = keyboard.nextInt();
System.out.println("HomeRuns: ");
homeVal = keyboard.nextInt();
S.add(new Player(surName, firstName, posName, heightVal, hitsVal, atBatsVal, singVal, doubVal, tripVal, homeVal, 0));
}
public static void changeHeight(ArrayList<Player> S)
{
int playerSel = 0;
int newHeight = 0;
Scanner keyboard = new Scanner(System.in); // Various user input
System.out.println("Select a player to enter the height for: ");
do
{
for (int i = 0; i < S.size(); i++) // Displays only the first/surNames of the players
{
System.out.print(i + ". " + S.get(i).getName());
System.out.println(" ");
}
playerSel = keyboard.nextInt();
System.out.println("Enter the height for this character: ");
newHeight = keyboard.nextInt();
if (newHeight < 125 && newHeight > 240)
{
System.out.println("WRONG! TRY AGAIN!");
}
else
{
}
} while (newHeight >= 125 && newHeight <= 240);
}
public static void BubbleSort(ArrayList<Player> S){
Player strTemp;
int i = 0;
boolean isSorted = false;
while(i < S.size()&&isSorted==false)
{
isSorted = true;
for(int j = 0; j < (S.size()-1)-i;j++)
{
if(S.get(j).getName().compareToIgnoreCase(S.get(j+1).getName())>0){
strTemp = S.get(j);
S.set(j,S.get(j+1));
S.set(j+1,strTemp);
isSorted = false;
}
}
i++;}
}
public static void InsertionSort(ArrayList<Player> S){ // hits over atbats
int outer;
double inner;
for(outer = 1; outer < S.size();outer++){
double keyItem = S.get(outer).getBatAvg();
inner = outer - 1 ;
while(inner >0&&S.get(inner-1).getBatAvg() > keyItem){
S.set((inner),S.get(inner-1));
inner--;
break;
}
double helpSort = S.get(inner).getBatAvg();
helpSort = keyItem;
}
}
}
class PlayerRip {
public String name;
public String name2;
public String position;
public int [ ] mark = new int[7];
public double [ ] batAvg = new double[1];
static class PlayerInfo extends PlayerRip
{
PlayerInfo() {
this.name = "-1";
this.name2 = "-1";
this.position = "-1";
for (int i=0; i < mark.length; i++)
mark[i] = -1;
}
PlayerInfo(String nam, String nam2, String pos, int a, int b, int c, int d, int e, int f, int g, double h) {
this.name = nam;
this.name2 = nam2;
this.position = pos;
this.mark[0] = a; this.mark[1] = b; this.mark[2] = c; this.mark[3] = d; this.mark[4] = e; this.mark[5] = f; this.mark[6] = g;
batAvg[0] = (((double)mark[1] / (double)mark[2]) * 100);
}
public void setName(String nam) { name = nam; }
public void setName2(String nam2) { name2 = nam2; }
public void setPosition(String pos) { position = pos; }
public void setMark(int index, int mark) { this.mark[index] = mark; }
public void setBatAvg(int index, double batAvg) {this.batAvg[index] = batAvg;}
public String getName() { return this.name; }
public String getName2() { return this.name2; }
public String getPosition() { return this.position; }
public double getBatAvg() { return this.batAvg[0];}
public int getMark(int index) { return this.mark[index]; }
public void setHeight(int index, int mark) { this.mark[index] = mark; }
public int getHeight(int index) { return this.mark[0]; }
public void setHits (int index, int mark) { this.mark [index] = mark; }
public int getHits (int index) { return this.mark [1]; }
public void setAtBats (int index, int mark) { this.mark [index] = mark; }
public int getAtBats(int index) { return this.mark [2]; }
public void setSingles (int index, int mark) { this.mark [index] = mark; }
public int getSingles (int index) { return this.mark [3] ; }
public void setDoubles (int index, int mark) { this.mark [index] = mark; }
public int getDoubles (int index) { return this.mark [4] ; }
public void setTriples (int index, int mark) { this.mark [index] = mark; }
public int getTriples (int index) { return this.mark [5] ; }
public void setHomeRuns (int index, int mark) { this.mark [index] = mark; }
public int getHomeRuns (int index) { return this.mark [6] ; }
}
}
sorry for format im new to the site
}
public static void InsertionSort(ArrayList<Player> S){ // hits over atbats
int outer;
double inner;
for(outer = 1; outer < S.size();outer++){
double keyItem = S.get(outer).getBatAvg();
inner = outer - 1 ;
while(inner >0&&S.get(inner-1).getBatAvg() > keyItem){
S.set((inner),S.get(inner-1));
inner--;
break;
}
double helpSort = S.get(inner).getBatAvg();
helpSort = keyItem;
}
}
}
is the specific area of problems

S.get() and S.set() take a int variable so cast inner to a int.

You defined inner as a double, and in Java, when you do math with a double and an int (such as inner - 1), you'll get a double as a result. This page has a fairly good explanation.
Then when you say S.get(inner - 1), you're saying to use a double as an the index in the ArrayList. The documentation for ArrayList.get says that you can only use an int as an index, and that's why you're getting a compiler error. You're also only allowed to use an int as the index for set, so that's why the compiler would complain about S.set(inner, ...).
You could just cast inner to an int, but it would be much better to declare it as an int in the first place since there's no reason it needs to be a double.

Related

Having trouble reseting game to previous round JAVA

I made a program which asks the user for their pet name and assigns it states of mind for 5 rounds. If the pet gets too angry it is put down.
What I am having trouble with is allowing the user to restart to an earlier stage at the game before the pet died.
Compiling the code would help illustrate the issue.
Any help would be appreciated.
import java.util.Random;
import java.util.Scanner;
class dinoo {
public static void main(String[] p) {
Pet p1 = new Pet();
Pet p2 = new Pet();
Scanner scanner = new Scanner(System.in);
String petname;
String species;
String angerlevel;
int thirst;
int hunger;
int irritability;
explain();
petname = askpetname();
species = askpetspecies();
int howmanyrounds = 5;
for (int i = 0; i < howmanyrounds; i++) {
int number = i + 1;
String num = Integer.toString(number);
print("Round " + number);
String[] emotionalstate = newarray(5);
thirst = thirstlevel(p1);
hunger = hungerlevel(p1);
irritability = irritabilitylevel(p1);
angerlevel = anger(hunger, thirst, irritability);
p1 = setpetname(p1, petname);
p1 = setspecies(p1, species);
p1 = setthirst(p1, thirst);
p1 = setanger(p1, angerlevel);
p1 = sethunger(p1, hunger);
p1 = setangervalue(p1, irritability);
print(petname + "'s thirst level is " + thirst + " , hunger level is " + hunger + ", irritability level is " + irritability + " and therefore emotional state is " + angerlevel);
if (angerlevel.equals("DANGEROUS")) {
print(petname + " is looking " + angerlevel + ", get out now! we will have to put " + petname + " down.");
boolean continueEnd = petdead();
if (continueEnd == false) {
System.exit(0);
} else {
emotionalstate = wheretogo(emotionalstate[]);
}
} else if (angerlevel.equals("Serene")) {
print("He looks " + angerlevel + ". Seems in a good mood.");
} else if (angerlevel.equals("Grouchy")) {
print("You should give him a treat to cheer him up.");
}
whatdoyouwant(p1);
print("Your pets emotion is now " + anger(getthirst(p1), gethungervalue(p1), getirritabilityvalue(p1)));
emotionalstate[i] = anger(getthirst(p1), gethungervalue(p1), getirritabilityvalue(p1));
print("Emotional state " + emotionalstate[i] + " has been saved!");
}
System.exit(0);
}
public static String[] wheretogo(String[] a) {
Scanner scanner = new scanner;
print("which level would you like to return to?");
int number = scanner.nextInt();
String level = a[number];
return a;
}
public static boolean petdead() {
Scanner scanner = new Scanner(System.in);
print("Your pet has been killed. Would you like to continue? (True or False)");
boolean yesorno = scanner.nextBoolean();
return yesorno;
}
public static int inputint(String message) {
Scanner scanner = new Scanner(System.in);
System.out.println(message);
int answer = scanner.nextInt();
return answer;
}
public static String[] newarray(int arraylength) {
String[] emotionalstate = new String[arraylength];
return emotionalstate;
}
//takes input from user to cheerup/feed/sing to the animal to lower values stored in setter/getter
public static Pet whatdoyouwant(Pet p1) {
Scanner scanner = new Scanner(System.in);
print("what would you like to do to the pet? (treat/water/sing)");
String ans = scanner.nextLine();
Random ran = new Random();
int reduction = ran.nextInt(6);
if (ans.equalsIgnoreCase("treat")) {
int hunger = gethungervalue(p1) - reduction;
if (hunger < 0) {
hunger = 0;
}
p1 = sethunger(p1, hunger);
print("Your pets hunger has been reduced to:");
printint(gethungervalue(p1));
} else if (ans.equals("sing")) {
int irrit = getirritabilityvalue(p1) - reduction;
if (irrit < 0) {
irrit = 0;
}
p1 = setirritability(p1, irrit);
print("Your pets irritability hs been reduced to:");
printint(getirritabilityvalue(p1));
} else if (ans.equals("water")) {
int thirst = getthirst(p1) - reduction;
if (thirst < 0) {
thirst = 0;
}
p1 = setthirst(p1, thirst);
print("Your pets thirst is has been reduced to:");
printint(getthirst(p1));
} else {
print("That action seems to agitate your pet, try something else before your pet becomes dangerous!");
}
return p1;
}
//GETTER METHOD
public static String getpetname(Pet p) {
return p.name;
}
public static String getspecies(Pet p) {
return p.species;
}
public static String getanger(Pet p) {
return p.anger;
}
public static int getthirst(Pet p) {
return p.thirst;
}
public static int gethungervalue(Pet p) {
return p.hunger;
}
public static int getangervalue(Pet p) {
return p.angervalue;
}
public static int getirritabilityvalue(Pet p) {
return p.irritability;
}
//SETTER METHOD
public static Pet setangervalue(Pet p, int whatsangervalue) {
p.angervalue = whatsangervalue;
return p;
}
public static Pet setpetname(Pet p, String name) {
p.name = name;
return p;
}
public static Pet setspecies(Pet p, String petspecies) {
p.species = petspecies;
return p;
}
public static Pet setanger(Pet p, String howangry) {
p.anger = howangry;
return p;
}
public static Pet sethunger(Pet p, int howhungry) {
p.hunger = howhungry;
return p;
}
public static Pet setthirst(Pet p, int howthirsty) {
p.thirst = howthirsty;
return p;
}
public static Pet setirritability(Pet p, int howirritable) {
p.irritability = howirritable;
return p;
}
//Method printing out statement to explain functionality of program
public static void explain() {
print("The following program demonstrates use of user input by asking for pet name.");
return;
}
//Method to ask the pet name
public static String askpetname() {
Scanner scanner = new Scanner(System.in);
print("Name your dinosaur pet!");
String petname = scanner.nextLine();
return petname;
}
//Method to ask the pet species
public static String askpetspecies() {
Scanner scanner = new Scanner(System.in);
print("What species is your pet?");
String petspecies = scanner.nextLine();
return petspecies;
}
//Randomly allocates thirst value 0-10
public static int thirstlevel(Pet p1) {
Random ran = new Random();
int thirst = ran.nextInt(11);
setthirst(p1, thirst);
return thirst;
}
//Randomly Allocates hunger value 0-10
public static int hungerlevel(Pet p1) {
Random ran = new Random();
int hunger = ran.nextInt(11);
sethunger(p1, hunger);
return hunger;
}
//randomly generates a irratibilty value
public static int irritabilitylevel(Pet p1) {
Random ran = new Random();
int irritable = ran.nextInt(11);
setirritability(p1, irritable);
return irritable;
}
//Method calculates the anger value based on the thirst/hunger/irritability average
public static String anger(int thirst, int hunger, int irritability) {
int angerscore = (thirst + hunger + irritability) / 3;
String temper;
temper = Integer.toString(angerscore);
if (angerscore <= 1) {
temper = "Serene";
} else if (angerscore <= 3) {
temper = "Grouchy";
} else if (5 < angerscore) {
temper = "DANGEROUS";
}
return temper;
}
//HELPER PRINT METHOD
public static String print(String message) {
System.out.println(message);
return message;
}
public static int printint(int message) {
System.out.println(message);
return message;
}
}//END class dinoo
class Pet {
String name;
String species;
int thirst;
int hunger;
String anger;
int irritability;
int angervalue;
} //END class pet
First of all you should look at the compile errors in your code before submitting a question here.
Please read the links provided in the comments to learn how to submit a proper question.
I tried to compile your code and it had the following errors:
java2.java:51: error: '.class' expected
emotionalstate = wheretogo(emotionalstate[]);
^
java2.java:75: error: '(' or '[' expected
Scanner scanner = new scanner;
That means in line 51, you're passing emotionalstate[] , which is emotional state array, whereas emotionalstate itself is an array, so you're passing an array of an array.
So just change it to emotionalstate = wheretogo(emotionalstate)
And in line 75, your initialization of Scanner object is wrong, change it to Scanner scanner = new Scanner();

Error: java.util.AbstractList$Itr cannot be cast to ex2.Tuple

I have a strange error in my code:
Exception in thread "main" java.lang.ClassCastException: java.util.AbstractList$Itr
cannot be cast to ex2.Tuple
at ex2.Main.main(Main.java:142)
since in the GradeBook class I have this declaration
private ArrayList courseLists;
I do not understand this cast Exception
here is my complete code:
the problem is in Main.java line 142:
Tuple tupleObject = (Tuple)iterator;
GradeBook.java :
package ex2;
import java.util.ArrayList;
public class GradeBook {
private ArrayList<Tuple> courseLists;
//final mark for the student
private float finalStudentmark;
public GradeBook(){
courseLists = new ArrayList<Tuple>();
finalStudentmark = 0;
}
public ArrayList<Tuple> getCourseLists() {
return courseLists;
}
public void setCourseLists(Tuple t) {
this.courseLists.add(t);
}
public float getFinalStudentmark() {
return finalStudentmark;
}
public void setFinalStudentmark(float finalStudentmark) {
this.finalStudentmark = finalStudentmark;
}
}
Main.java :
package ex2;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Random;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import static java.util.concurrent.TimeUnit.*;
public class Main {
public static void main(String[] args) {
//1- create 10 courses
Course[] courseLists = new Course[10];
for(int i=0; i<10; i++){
//create
Course course = new Course("course"+i, "courseId"+i, "", 60.0f, 0, 0.0f);
courseLists[i]=course;
}
//2- create 7 professors
Professor[] professorLists = new Professor[7];
Random rand= new Random();
int min=1;
int max = 6;
for(int i=0; i<7; i++){
//create
Professor professor = new Professor("ProfessorFirstName"+i, "ProfessorLastName"+i, 35, "MALE", "adress"+i, "professorId"+i);
courseLists[i].setAssignedProfessor("profId"+i);
professor.setCourseList(courseLists[i]);
professorLists[i] = professor;
}
rand= new Random();
int randomNum1 = rand.nextInt((max - min) + 1) + min;
int randomNum2 = rand.nextInt((max - min) + 1) + min;
while ( randomNum2 == randomNum1 ) {
randomNum2 = rand.nextInt((max - min) + 1) + min;
}
courseLists[8].setAssignedProfessor("profId"+randomNum1);
professorLists[randomNum1].setCourseList(courseLists[8]);
courseLists[9].setAssignedProfessor("profId"+randomNum2);
professorLists[randomNum2].setCourseList(courseLists[9]);
courseLists[7].setAssignedProfessor("profId"+1);
professorLists[1].setCourseList(courseLists[7]);
//3- create 30 students
Student[] studentsLists = new Student[30];
//--------------------
boolean genderValue;
//generate number of courses per student
//randomNbrCourses: number of courses taken by the current student
for(int i=0; i<30; i++){
int minNbrCourses = 1;
int maxNbrCourses = 6;
int randomNbrCourses;
rand= new Random();
randomNbrCourses = rand.nextInt((maxNbrCourses - minNbrCourses) + 1) + minNbrCourses;
//generate random age
int minStudentAge=18;
int maxStudentAge = 48;
int randomAge = -1;
rand= new Random();
randomAge = rand.nextInt((maxStudentAge - minStudentAge) + 1) + minStudentAge;
//gender
genderValue = Math.random() < 0.5;
String gender;
if (genderValue == false)
gender = "FEMALE";
else
gender = "MALE";
HashSet<Integer> tempSet;
tempSet = new HashSet<Integer>();
GradeBook gradeBook = new GradeBook();
for ( int nbrCourse=0; nbrCourse<randomNbrCourses; nbrCourse++) {
Tuple tupleValue = new Tuple();
//generate one number , this number correspand to a course id...
int randomNumber = rand.nextInt(10);
tempSet.add(randomNumber);
while (tempSet.contains(randomNumber))
randomNumber = rand.nextInt(10);
tempSet.add(randomNumber);
courseLists[randomNumber].setNbrEnrolledStudent(1);
Random newRand= new Random();
//generate four random marks for the course....
float randomMark1 = newRand.nextFloat()*(100.0f-0.0f) + 0.0f;
tupleValue.setMarkExam1(randomMark1);
float randomMark2 = newRand.nextFloat()*(100.0f-0.0f) + 0.0f;
tupleValue.setMarkExam2(randomMark2);
float randomMark3 = newRand.nextFloat()*(100.0f-0.0f) + 0.0f;
tupleValue.setMarkExam3(randomMark3);
float randomMark4 = newRand.nextFloat()*(100.0f-0.0f) + 0.0f;
tupleValue.setMarkExam4(randomMark4);
tupleValue.setFinalMark((randomMark1+randomMark2+randomMark3+randomMark4)/4);
tupleValue.setCourseName("course"+randomNumber);
tupleValue.setCourseId("courseId"+randomNumber);
gradeBook.setCourseLists(tupleValue);
}
Student student = new Student("firstName_student"+i, "lastName_student"+i, randomAge, gender, "adress"+i, "idStudent"+i, null ,gradeBook);
//for quick access, add courses ids
Iterator<Tuple> iterator = (Iterator<Tuple>) gradeBook.getCourseLists().iterator();
while (iterator.hasNext()) {
Tuple tupleObject = (Tuple)iterator;
student.getCourseLists().add(tupleObject.getCourseId());
}
studentsLists[i]=student;
studentsLists[i].setNbrCourses(randomNbrCourses);
}
//we have to verify that there is no course with less than 3 student enrolled
//create the admin thread
//1- create a schedule for the exam
HashMap<String, float[]> examScheduleMap;
examScheduleMap = new HashMap <String, float[]>();
//ExamSchedule eSchedule = new ExamSchedule();
Thread examSchedTh = new Thread( new ExamSchedule(examScheduleMap, courseLists));
examSchedTh.start();
try {
examSchedTh.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
//using thread pool and scheduler for students
// 1- thread pool
ScheduledThreadPoolExecutor eventPool = new ScheduledThreadPoolExecutor(30);
for (int j=0;j<30;j++)
eventPool.schedule(new StudentThread(courseLists, studentsLists, j), 0, SECONDS);
//for (int i=0; i<30;i++)
// thPoolStudent[i] = new Thread( new StudentThread(courseLists));
//th1.start();
//wait for the exam period
//print the list of courses
getWholeCouces(courseLists, studentsLists);
//print the professors and there assigned courses
getProfessorsAndAssignedCouces(professorLists);
//print the list of all students and the courses enrolled in
getStudentsWithEnrolledCourses(studentsLists);
}
/*
static float getMinMarkCourse(){
}
static float getMaxMarkCourse(){
}
static float getGroupMarkCourse(){
}*/
//method to print the list of all students and the courses they are enrolled in
static void getStudentsWithEnrolledCourses(Student[] student){
System.out.println(" ");
System.out.println("----------------------------------------------------------");
System.out.println("list of all students and the courses they are enrolled in:");
System.out.println("----------------------------------------------------------");
for (int i=0; i<30;i++){
System.out.print(student[i].getLastName());
System.out.print(" "+student[i].getIdentificationNumber());
GradeBook gb = student[i].getGradeBook();
ArrayList<Tuple> tuple = gb.getCourseLists();
for (int L=0; L< tuple.size(); L++)
{
System.out.println(" ");
System.out.print(" "+tuple.get(L).getCourseId());
System.out.print(" "+tuple.get(L).getFinalMark());
}
System.out.println(" ");
System.out.println(" ");
}
}
//method to get the professors and there assigned courses
static void getProfessorsAndAssignedCouces(Professor[] professor){
System.out.println(" ");
System.out.println("---------------------------------------");
System.out.println("professors and there assigned courses:");
System.out.println("---------------------------------------");
for(int i=0; i<7; i++){
System.out.println(" ");
System.out.print(professor[i].getFirstName());
System.out.print(" "+professor[i].getIdentificationNumber());
System.out.println(" ");
System.out.println(" ");
List<Course> courseList = professor[i].getCourseList();
for (int k=0; k < courseList.size(); k++){
System.out.print(" "+courseList.get(k).getCourseId());
System.out.print(" "+courseList.get(k).getNbrEnrolledStudent());
System.out.print(" "+courseList.get(k).getAverageCourseMark());
System.out.println(" ");
}
System.out.println(" ");
}
}
//method to get the list of all courses
static void getWholeCouces(Course[] courseList,Student[] studentsList){
System.out.println("----------------");
System.out.println("list of courses:");
System.out.println("----------------");
// maxMark = max mark of the course
// minMark = minimum mark of the course
float maxMark = Float.MIN_VALUE;
float minMark = Float.MAX_VALUE;
float allMarks = 0.0f;
float nbOfEnrolledStudent=0.0f;
for(int i=0; i<10; i++){
//create
String courseName = courseList[i].getCourseName();
//look for enrolled student
for(int nbStudent=0; nbStudent<30; nbStudent++){
ArrayList<Tuple> temp = studentsList[nbStudent].getGradeBook().getCourseLists();
for (int j=0;j< temp.size();j++){
if (temp.get(j).getCourseName().equals(courseName)){
if (temp.get(j).getFinalMark() > maxMark )
maxMark = temp.get(j).getFinalMark();
if (temp.get(j).getFinalMark() < minMark )
minMark = temp.get(j).getFinalMark();
allMarks += temp.get(j).getFinalMark();
nbOfEnrolledStudent+=1;
}
}
}
courseList[i].setAverageCourseMark((allMarks)/nbOfEnrolledStudent);
System.out.print(courseName);
System.out.print(" "+courseList[i].getCourseId());
System.out.print(" "+courseList[i].getAssignedProfessor());
System.out.print(" "+courseList[i].getNbrEnrolledStudent());
System.out.print(" "+minMark);
System.out.print(" "+maxMark);
System.out.print(" "+(allMarks)/nbOfEnrolledStudent);
System.out.println(" ");
}
}
}
Tuple.java :
package ex2;
public class Tuple{
private String courseName;
private String courseId;
private float markExam1;
private float markExam2;
private float markExam3;
private float markExam4;
private float finalMark;
//default constructor
public Tuple(){
super();
courseName = "";
courseId = "";
markExam1 = 0;
markExam2 = 0;
markExam3 = 0;
markExam4 = 0;
finalMark = 0;
}
public String getCourseId() {
return courseId;
}
public void setCourseId(String courseId) {
this.courseId = courseId;
}
public Tuple(String courseName, String courseId, float markExam1, float markExam2, float markExam3, float markExam4, float finalMark) {
this.courseName = courseName;
this.courseId = courseId;
this.markExam1 = markExam1;
this.markExam2 = markExam2;
this.markExam3 = markExam3;
this.markExam4 = markExam4;
this.finalMark = finalMark;
}
public String getCourseName() {
return courseName;
}
public void setCourseName(String courseName) {
this.courseName = courseName;
}
public float getMarkExam1() {
return markExam1;
}
public void setMarkExam1(float markExam1) {
this.markExam1 = markExam1;
}
public float getMarkExam2() {
return markExam2;
}
public void setMarkExam2(float markExam2) {
this.markExam2 = markExam2;
}
public float getMarkExam3() {
return markExam3;
}
public void setMarkExam3(float markExam3) {
this.markExam3 = markExam3;
}
public float getMarkExam4() {
return markExam4;
}
public void setMarkExam4(float markExam4) {
this.markExam4 = markExam4;
}
public float getFinalMark() {
return finalMark;
}
public void setFinalMark(float finalMark) {
this.finalMark = finalMark;
}
}
Replace
Tuple tupleObject = (Tuple)iterator;
with
Tuple tupleObject = iterator.next();
You can't cast the iterator to a Tuple. call the next method on iterator instead:
while (iterator.hasNext()) {
Tuple tupleObject = iterator.next();
student.getCourseLists().add(tupleObject.getCourseId());
}

Variables used in my method are showing errors and are unresolved

So, i was using some variables in my methods but I get errors and I dont know how to fix this heres my code from my first class:
import java.util.Scanner;
public class Gerbilfood {
public static void main(String[] args) {
Gerbil[] gerbil;
Scanner scanner = new Scanner(System.in);
System.out.println("Please input how many types of food items the gerbils eat as an integer");
String n0 = scanner.nextLine();
int n1 = Integer.parseInt(n0);
String[] food = new String[n1];
for (int i = 0; i < n1; i++) {
System.out.println("Please enter a food name");
String n2 = scanner.nextLine();
food[i] = n2;
int[] maximum = new int[n1];
System.out.println("Please enter maximum amount of food per day");
String n33 = scanner.nextLine();
int n3 = Integer.parseInt(n33);
maximum[i] = n3;
}
System.out.println("Please enter in the number of gerbils in the lab");
String n73 = scanner.nextLine();
int n4 = Integer.parseInt(n73);
gerbil = new Gerbil[n4];
int[] combo = new int[n4];
String[] ids = new String[n4];
for (int i = 0; i < n4; i++) {
Gerbil g = new Gerbil(n1);
System.out.println("Please enter in the lab id for each gerbil");
String n5 = scanner.nextLine();
g.setId(n5);
//ids[i] = n5;
//String[] names = new String[n4];
System.out.println("Please enter in the name of each gerbil");
String n6 = scanner.nextLine(); // gerbil name
g.setName(n6);
String[] amountfood = new String[n1];
for (int j = 0; j < n1; j++) {
System.out.println("how much of" + food[j] + "did the gerbil eat");
String n8 = scanner.nextLine();
amountfood[i] = n8;
}
String[] bite = new String[n4];
System.out.println("Does this Gerbil bite? Enter True or False");
String n77 = scanner.nextLine();
bite[i] = n77;
String[]escape = new String[n4];
System.out.println("Does this Gerbil escape? Enter True or False");
String n89 = scanner.nextLine();
escape[i] = n89;
}
System.out.println("What information would you like to know?");
String n55 = scanner.nextLine();
String n33 = "search";
String n34 = "average";
String n35 = "restart";
String n36 = "quit";
if(n55.equalsIgnoreCase(n34)) {
System.out.println(averagefood());
} else {
if(n55.equalsIgnoreCase(n33)) {
System.out.println("Please type the lab id of the gerbil you wish to search for");
String n87 = scanner.nextLine();
System.out.println();
} else {
if (n55.equalsIgnoreCase(n35)) {
//go back to beginning of program
} else {
if (n55.equalsIgnoreCase(n36)) {
System.exit(0);
} else {
System.out.println("ERROR");
}
}
}
}
}
public static int averagefood(int n4, int n3, int n8) {
for (int i = 0; i < n4; i++) {
long percent = Math.round(n8 * 100.0 / n3);
return averagefood(newName, newId, percent);
}
}
public static int searchForGerbil() {
n87 = setId;
return 0;
// return (new Gerbil[i]
and heres the code from my second class:
public class Gerbil {
private String id;
private String name;
private int[] amountfood;
//private int numbergerbils;
//private int maxfood;
private boolean escape;
private boolean bite;
public Gerbil(String n5, String n6, int numOfFood, boolean newEscape, boolean newBite) {
id = n5;
name = n6;
amountfood = new int[numOfFood];
escape = newEscape;
bite = newBite;
}
public Gerbil(int numOfFood) {
amountfood = new int[numOfFood];
}
public String getId() {
return id;
}
public String getName() {
return name;
}
public void setId(String newId) {
id = newId;
}
public void setName(String newName) {
name = newName;
}
}
it says next to System.out.println(averagefood()); The method
averagefood(int, int, int) in the type Gerbilfood is not applicable
for the arguments ()
If you check your code your function definition requires three arguments and you have not passed any.
getName cannot be resolved to a variable
This is a function in class Gerbil and hence needs to be called as follows:
Gerbil gb = new Gerbil();
gb.getName();
Syntax error on token "return", Name expected after this token - getId
cannot be resolved to a variable - newId cannot be resolved to a
variable - newName cannot be resolved to a variable it says that next
to return averagefood(newName, newId, percent);
None of these variables have been defined in class Gerbilfood. What values are you expecting to pass using these variables?

average method arrays hint

Can you give me a hint on what I'm doing wrong with my average in the average method? I'm trying to call the method in the read scores.I'm trying to get the average of the scores I have in my input.txt file.
import java.io.*;
import java.util.*;
public class FindGrade {
public static final int NUM_SCORE_TYPES = 5;
public static void main(String[] args) {
Scanner scan = null;
int[] quizArray = null;
int[] labArray = null;
int[] attendance = null;
int[] midterms = null;
int quizgrade =0;
int labgrade=0;
int attendance_1=0;
int midterms_1 =0;
String name;
try {
scan = new Scanner(new File("input.txt"));
} catch (FileNotFoundException e) {
e.printStackTrace();
return;
}
// each iteration is for single exam type (ie: Quizzes is the 1st one)
for (int i = 0; i < NUM_SCORE_TYPES; i++) {
name = scan.next();
int numScores = scan.nextInt();
int maxGrade = scan.nextInt();
if (name.equals("Quizzes")) {
quizArray = new int[numScores];
readScores(quizArray, numScores, scan);
}
else if (name.equals("Labs")) {
labArray = new int[numScores];
readScores(labArray, numScores, scan);
}
else if (name.equals("Lab_attendance")) {
attendance = new int[numScores];
readScores(attendance, numScores, scan);
}
else if (name.equals("Midterms")) {
midterms = new int[numScores];
readScores(midterms, numScores, scan);
}
}
}
public static void readScores(int[] scoreArray, int numScores, Scanner scan) {
for (int i = 0; i < numScores; i++) {
scoreArray[i] = scan.nextInt();
}
}
public static void average(double [] scoreArray, int numScores){
double sum=0;
for(int i=0; i< scoreArray.length; i++){
sum += scoreArray[i];
}
double average = sum/numScores;
System.out.println(sum + " " + average);
}
In any case, you can't directly call it with the arrays that you are creating there. Because the arrays are of type int, but the average-method requires a double array. When you change this, you can call the method like this...
public static void readScores(int[] scoreArray, int numScores, Scanner scan) {
for (int i = 0; i < numScores; i++) {
scoreArray[i] = scan.nextInt();
}
average(scoreArray, numScores); // <----- Call it here
}
public static void average(int[] scoreArray, int numScores){
double sum=0;
for(int i=0; i< scoreArray.length; i++){
sum += scoreArray[i];
}
double average = sum/numScores;
System.out.println(sum + " " + average);
}

Forked Java VM exited abnormally. JUnit Test?

I have a simple Java program that seems to work well until uploaded to my school's grading system, "WebCat", which I'm assuming is just running JUnit. The error it kicks back is:
Forked Java VM exited abnormally. Please note the time in the report does not reflect the >time until the VM exit.
I've researched this issue and and the main first troubleshooting step seems to be to look at the dump log. Unfortunately I cannot do that in this case. I am really at a loss on how to begin to troubleshoot this considering the lack of feedback from the grading system and the lack of compile or run-time errors.
Here is the code if anyone is familiar with this error or can at least give me some direction of where to begin troubleshooting. Much appreciated!
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.Scanner;
import java.io.IOException;
class PlayerApp {
public static void showMenu()
{
System.out.println("Player App Menu");
System.out.println("P - Print Report");
System.out.println("A - Add Score");
System.out.println("D - Delete Score");
System.out.println("L - Find Lowest Score");
System.out.println("H - Find Highest Score");
System.out.println("Q - Quit");
}
public static void main(String[] args) throws IOException
{
if (args.length == 0)
{
System.out.println("File name was expected as a run argument.");
System.out.println("Program ending.");
System.exit(0);
}
String fileName = args[0];
Scanner sc = new Scanner(System.in);
String stnew = "";
boolean exit = false;
Player p = null;
double[] scoreList;
File dbFile = new File(fileName);
FileInputStream fis = new FileInputStream(fileName);
InputStreamReader inStream = new InputStreamReader(fis);
BufferedReader stdin = new BufferedReader(inStream);
String name = stdin.readLine();
stnew = stdin.readLine();
int numScore = Integer.parseInt(stnew);
scoreList = new double[numScore];
for (int i = 0; i < numScore; i++)
{
stnew = stdin.readLine();
scoreList[i] = Double.parseDouble(stnew);
}
p = new Player(name, numScore, scoreList);
stdin.close();
System.out.println("File read in and Player object created.");
showMenu();
while (exit == false)
{
System.out.print("\nEnter Code [P, A, D, L, H, or Q]:");
String choice = sc.nextLine().toLowerCase();
if (choice.equals("p"))
{
System.out.println(p.toString());
}
else if (choice.equals("a"))
{
System.out.print(" Score to add: ");
stnew = sc.nextLine();
double scoreIn = Double.parseDouble(stnew);
p.addScore(scoreIn);
}
else if (choice.equals("d"))
{
System.out.print(" Score to delete: ");
stnew = sc.nextLine();
double scoreIn = Double.parseDouble(stnew);
p.deleteScore(scoreIn);
System.out.println(" Score removed.");
}
else if (choice.equals("l"))
{
System.out.println(" Lowest score: " + p.findLowestScore());
}
else if (choice.equals("h"))
{
System.out.println(" Highest score: " + p.findHighestScore());
}
else if (choice.equals("q"))
{
exit = true;
}
}
}
}
break
import java.text.DecimalFormat;
public class Player {
//Variables
private String name;
private int numOfScores;
private double[] scores = new double[numOfScores];
//Constructor
public Player(String nameIn, int numOfScoresIn, double[] scoresIn) {
name = nameIn;
numOfScores = numOfScoresIn;
scores = scoresIn;
}
//Methods
public String getName() {
return name;
}
public double[] getScores() {
return scores;
}
public int getNumScores() {
return numOfScores;
}
public String toString() {
String res = "";
DecimalFormat twoDForm = new DecimalFormat("#,###.0#");
DecimalFormat twoEForm = new DecimalFormat("0.0");
res += " Player Name: " + name + "\n Scores: ";
for (int i = 0; i < numOfScores; i++)
{
res += twoDForm.format(scores[i]) + " ";
}
res += "\n Average Score: ";
res += twoEForm.format(this.computeAvgScore());
return res;
}
public void addScore(double scoreIn) {
double newScores[] = new double[numOfScores +1 ];
for (int i = 0; i < numOfScores; i++)
{
newScores[i] = scores[i];
}
scores = new double[numOfScores + 1];
for(int i = 0; i < numOfScores; i++)
{
scores[i] = newScores[i];
}
scores[numOfScores] = scoreIn;
numOfScores++;
}
public boolean deleteScore(double scoreIn) {
boolean found = false;
int index = 0;
for (int i = 0; i < numOfScores; i++)
{
if (scores[i] == scoreIn)
{
found = true;
index = i;
}
}
if (found == true)
{
double newScores[] = new double[numOfScores -1 ];
for (int i = 0; i < index; i++)
{
newScores[i] = scores[i];
}
for (int i = index + 1; i < numOfScores; i++)
{
newScores[i - 1] = scores[i];
}
scores = new double[numOfScores - 1];
numOfScores--;
for (int i = 0; i < numOfScores; i++)
{
scores[i] = newScores[i];
}
return true;
}
else
{
return false;
}
}
public void increaseScoresCapacity()
{
scores = new double[numOfScores + 1];
numOfScores++;
}
public double findLowestScore() {
double res = 100.0;
for (int i = 0; i < numOfScores; i++)
{
if (scores[i] < res)
{
res = scores[i];
}
}
return res;
}
public double findHighestScore() {
double res = 0.0;
for (int i = 0; i < numOfScores; i++)
{
if (scores[i] > res)
{
res = scores[i];
}
}
return res;
}
public double computeAvgScore() {
double res = 0.0;
if (numOfScores > 0) {
for (int i = 0; i < numOfScores; i++)
{
res += scores[i];
}
return res / (double)(numOfScores);
}
else {
//res = 0.0;
return res;
}
}
}
Your program is calling System.exit(0) for certain inputs. Don't do that! That's exactly what the message is telling you: that the JVM exited in the middle of the text, before the scoring code could finish up. Instead of calling exit(), just use return to return from main() early.
The library System Rules has a JUnit rule called ExpectedSystemExit. With this rule you are able to test code, that calls System.exit(...).

Categories

Resources