Java cycling through objects - java

I'm trying to cycle through objects and update a variable each time, I have a Player class that has all of the following variables:
Name, s1 ,s2, s3,...., s11, total
I want to go through each variable from the start to the end and adding the score at each go for each player (all the players are in an array list).
I'm not sure what the best way to do this is, is there a way to select a specific object and then add the variable depending on who go it is.
if you need any more information please ask and thanks in advance for any help given.
public void addScore(int turn, int score){
Player.setScore( turn, score);
}

You can cycle in array list with a simple for, like this:
ArrayList<Player> players = ...;
for (int i = 0; i < players.size(); i++) {
/*Operations on players[i] = the current player*/
}
To take and modify the variables of your player you can create getter and setter methods for each parameter like this:
private String name;
public String getName(){
return name;
}
public void setName(String name){
this.name = name;
}
If you have a lot of variables (s1, s11) of the same type, use an array:
int[] scores = new int[11];
So you can use another for cycle.

If I understand this question correctly, each player has a name, 11 scores, and a total. You seem to be asking how to iterate through a list of players and make the total equal to the sum of the 11 scores.
A more usual (in an OO language) approach would be just to ensure that the total is always equal to the sum of the 11 scores. (This is called "encapsulation", and is the fundamental idea behind all of object-oriented programming.) This is very easy to accomplish (for ease of programming, I put the scores in an array):
public class Player {
private String name ;
private int[] scores ;
private int total ;
public Player(String name) {
this.name = name ;
this.scores = new int[11] ; // all initialized to zero, as is total.
}
public void setScore(int whichScore, int score) {
int change = score - scores[whichScore] ;
scores[whichScore] = score ;
total = total + change ;
}
public int getScore(int whichScore) {
return scores[whichScore] ;
}
public int getTotal() {
return total ;
}
public String getName() {
return name ;
}
public void setName(String name) {
this.name = name ;
}
}
Now your question is redundant: the total is always equal to the sum of the scores, so there is no need to iterate through the players to compute the total anywhere in your code. You can get the total for each player with
for (Player p : listOfPlayers) {
System.out.println("Player "+p.getName()+" has total score "+p.getTotal());
}

Related

Index out of bounds for an array (java)

My code is supposed to print out the student with the highest range. There is a method in my Student class which calculates the range, while in my Classroom class there is another method that determines which student had the highest growth. My problem comes in the class Student, I get an Out of Bounds Exception in the addExamScore method.
Main class:
public class ClassroomTester
{
public static void main (String[] args)
{
Classroom c = new Classroom(2);
Student ada = new Student("Ada", "Lovelace", 12);
ada.addExamScore(44);
ada.addExamScore(65);
ada.addExamScore(77);
Student alan = new Student("Alan", "Turing", 11);
alan.addExamScore(38);
alan.addExamScore(24);
alan.addExamScore(31);
c.addStudent(ada);
c.addStudent(alan);
c.printStudents();
Student mostImproved = c.getMostImprovedStudent();
System.out.println("The most improved student is " + mostImproved.getName());
}
}
Student class:
public class Student
{
private static final int NUM_EXAMS = 4;
private String firstName;
private String lastName;
private int gradeLevel;
private double gpa;
private int[] exams;
private int numExamsTaken;
public Student(String fName, String lName, int grade)
{
firstName = fName;
lastName = lName;
gradeLevel = grade;
exams = new int[numExamsTaken];
numExamsTaken = 0;
}
public int getExamRange()
{
int maximum = 0;
int minimum = 0;
for(int i = 0; i < exams.length; i++){
if(exams[i]<exams[minimum]){
minimum = i;
}
else if(exams[i]>exams[maximum]){
maximum = i;
}
}
return exams[maximum]-exams[minimum];
}
public String getName()
{
return firstName + " " + lastName;
}
public void addExamScore(int score)
{
exams[numExamsTaken] = score;
numExamsTaken++;
}
public void setGPA(double theGPA)
{
gpa = theGPA;
}
public String toString()
{
return firstName + " " + lastName + " is in grade: " + gradeLevel;
}
}
First, you're initializing exams in the constructor the line before you initialize numExamsTaken, the order should be reversed because you need to know what numExamsTaken is before using it. I'd recommend storing the maximum and minimum as scores instead of indexes but that's just personal preference I think it makes the code more readable, so up to you. The index out of bounds problem probably has to do with your addExamScore method. If you've taken 4 exams it might look like [90, 85, 74, 82] where the indexes are 0, 1, 2, 3 and numExamsTaken = 4. Indexes starting at 0 is called zero-indexing and is used in most if not all programming languages.
exams[3] = 82 and exams[4] is going to give you an out of bounds error. Since you're not using an arrayList every time you want to add an element you're going to need to create an empty array of one size bigger than your current array, copy the previous scores over, and slide the new score into the last slot (in the case above would be index 4, which isn't out of bounds in the new array). Store your new array where your old array was in exams[].
Index out of bounds exception shows when array crosses it limits to store the value.
You have declared array of size '0' inside the constructor
in the line exams = new int[numExamsTaken];
initialize the size of the array with your expected range or use ArrayList to add values without specifying the size in prior
The problem with your code here is that you are trying to access a value in an array, which has not been allocated there. This is why the output is giving a ArrayIndexOutOfBoundsException, since you are trying to access an index in an array that is out of bounds of the array. In Java, arrays are fixed in size, meaning once you call new on an array, you cannot change the size of it without calling new on another array with a different size. In this case, it will be easiest to use a List, like an ArrayList, which does all of the resizing, copying, etc. for you, so you can use it as if it were a dynamically sized array. Your code would change to look something like this:
public class Student
{
// ...
private List<Integer> exams;
// ...
public Student(String fName, String lName, int grade)
{
// ...
exams = new ArrayList<>();
// ...
}
public int getExamRange()
{
int maximum = 0;
int minimum = 100;
for(int i = 0; i < exams.length; i++){
if (exams.get(i) > maximum) {
maximum = exams.get(i);
}
if (exams.get(i) < minimum) {
minimum = exams.get(i);
}
}
return maximum - minimum;
}
public void addExamScore(int score)
{
exams.add(score);
numExamsTaken++;
}
}
You can look more into List and ArrayList documentation at the java API website. Also, your logic for getting the minimum element is not correct, since if you have no scores that are less than 0, it will always assume that the minimum score is 0. You can fix this by setting the initial value to 100(the maximum possible value of a test score), or using another method that you prefer.

Insert two arrays in one using two methods for each array

i want to create 3 arrays with objects.The two arrays(pin and age) i want to put them on one array named Alltogether.I use from each method to return me an array i dont know if this is right i try it.In the end i want to systemout only the array that has all this.
package worklin1;
public class worklin1{
static int N; //from keyboard i have a class userinput
private String Name; // name
private int age; // age
private int costVehicle; //vehicle
public worklin1(){}
public worklin1(String Name, int Age, int cost, String name) {
Name=name;
Age=age;
costVehicle=cost;
}
// Access methods
public String getName(){
return Name;
}
public int getAge(){
return age;
}
public int getcostVehicle(){
return costVehicle;
}
// Mutator methods
public void setName(String name){
Name=name;
}
public void setSurname(String age){
age=age;
}
public void setcostVehicle(int cost){
costVehicle=cost;
}
public String toString() {
String s=name+" "+age+", "+cost+"\t";
return s;
}
public static void main(String[] args){ //main
int[] pin= new int[N]; // the first array
int[] age=new int[]; // the second array.i dont know why it is false this array maybe i use an object as name for an array thats why its false.
Allmethodtogether[] pin = new Allmethodtogether[N]; // Allmethodotogether is an array.It has the combination of age and the cost.The N is just a number i give from keyboard i dont care about this right now.I just wanted to focus on my problem which is how to combine the two methods(which they give me each one 2 arrays and i will add them in this array name Allmethodtogether).
for (int i = 0; i < 10; i++) { // i want to put in an array all the arrays from the methods so i start the counting from 0 until 10.Until the 10 will be saved the pin and after 10 will be saving the array age
Allmethodtogether[i] = new Vehcost();
Allmethodtogether[i+10] = new AllAge();
} //finished //Now i want to display those arrays and i am trying this .
int y; // i create a variable to save my results from the method
y=worklin1.Vehcost(int[] pin); // i take the result from the method Vehcost
System.out.println("Appear all array"+y ); //i want to appear the array.Did i create and an array with objects?
int k; // i do the same thing as the other
k=worklin1.Allage(int[] age);
System.out.println("Appear all array"+k);
} // end main
public static int Vehcost(int[] pin ) { //starting first method 1
int cost = 0;
for(int i =0; i < pin.length; i++) {
cost += pin[i].getcostVehicle();
pin[i]=getname()+ cost; //i want to save to pin the names and the cost of each one
}
return pin[i]; // i want to return the array pin
}//end method 1
public static int allAge(int[] age ) { //second method
if(getage() >18 ){ //if age is >18 only then will going to save on the array
for(int i =0; i < age.length; i++) {
age += age[i].getage();
}
}
return age; // i want to return the array age
}// end method 2
}

How to change the position within the array

I have one class which is called people where I keep track of 50 people, their rank, name, age and order. Then I have a second class called rearrange where I have to change the position of the int order. So it will change up the order, like order 1 which is in position 0, will be moved to position 48th. I need to do the whole thing without using any loop.
class people {
int order[] = new int[50];
for(int j=0; j<order.length; j++) {
order[j] = "order" + j;
System.out.print(order);
}
}
class rearrange {
// In here i need to change the position of the int order, and need to do this without using any loop.
}
Shouldn't rearrange be a method of the people class? Classes are usually created for Nouns, Verbs are usually functions or methods of a class. And wouldn't it be better to have a class "Person" and make an array of 50 of them, and simply change their index to change their order?
Consider something like this:
public class Person //create Person class with the attributes you listed
{
private int rank;
private int age;
private String name;
public Person(int rank, int age, String name) //constructor
{
this.rank = rank;
this.age = age;
this.name = name;
}
}
public class MainClass
{
Person[] people = new Person[50]; //array of Persons, containing 50 elements
public static void main(String[] args)
{
for(int i = 0; i < people.length(); i++)
{
people[i] = new Person(something, something, something); //give all the people some values, you'll have to decide what values you are giving them
}
//do something with the rearrange function here
}
public static void rearrange(int target, int destination) //this is just a "swap" function
{
Person temp = people[destination];
people[destination] = people[target];
people[target] = temp;
}
}

java - find the max value from a linked list

Disclaimer: I am a very early student and am struggling to learn java. Please tell me if I'm leaving out any important information.
I am writing a program that prompts the user to do various operations to a linked list (add, remove, change value, etc.) but rather than storing a string or some primitive data type I am storing objects of type Student (which basically contains a string for the name of the student and an integer for their test score) and am stuck on how to find the maximum test score since I can't just find the highest Student.
Any help would be appreciated.
Well you can have two variables, one as the currentScore, and another as the newScore. And then traverse through each student object, get the test value, and then compare. If the new score is lower, then keep current. If new score is higher, replace current score with new score, and keep traversing. When you traverse the list, you have the highest score
You can iterate over the list as other answers described or you can use Collections.max method. To use this method your Student class should implement comperable interface.
public class Student implements Comparable<Student>
and you need to add compareTo method to the class:
#Override
public int compareTo(Student student)
{
if (this.score > student.score)
{
return 1;
}
if (this.score < student.score)
{
return -1;
}
else
{
return 0;
}
}
Now when you write Collections.max(list) you will get the Student with the highest score.
I wrote a simple program that matched your case.
Main Class:
import java.util.*;
import java.lang.Math;
public class FindHighestScore
{
public static void main(String[] args)
{
LinkedList<Student> studentLinkedlist = new LinkedList<Student>();
studentLinkedlist.add(new Student("John",1)); // Adding 5 students for testing
studentLinkedlist.add(new Student("Jason",5));
studentLinkedlist.add(new Student("Myles",6));
studentLinkedlist.add(new Student("Peter",10)); // Peter has the highest score
studentLinkedlist.add(new Student("Kate",4));
int temp = 0; // To store the store temporary for compare purpose
int position = 0; // To store the position of the highest score student
for(int i = 0; i < studentLinkedlist.size(); i ++){
if(studentLinkedlist.get(i).getScore() > temp){
temp = studentLinkedlist.get(i).getScore();
position = i;
}
}
System.out.println("Highest score is: " + studentLinkedlist.get(position).getName());
System.out.println("Score: " + studentLinkedlist.get(position).getScore());
}
}
The student constructor class:
public class Student
{
String name;
int score;
Student(){
}
Student(String name, int score){
this.name = name;
this.score = score;
}
String getName(){
return this.name;
}
int getScore(){
return this.score;
}
}
The above program produce result as follows:
Highest score is: Peter
Score: 10

search arraylist by id-java

The following program asks to give the number of the players and their names. I want to put the names in a arraylist and return them by their id.
private static ArrayList<Player>Playerlist=new ArrayList<Player>();
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String s;
{
System.out.printf("number of players(2 -4)? ");
int p = scanner.nextInt();
scanner.nextLine();
for(int i=0;p>4 || p<2;i++)
{
System.out.printf("only 2-4 players.\n");
System.out.printf("number of players(2 -4)?");
p = scanner.nextInt();
scanner.nextLine();
}
Player pl=new Player();
int m=1;
for(int k=1;k<=p;k++)
{
System.out.printf("give the name of the player %d: ",k);
s= scanner.nextLine();
pl.setName(s,m);
System.out.printf(pl.getName());
Playerlist.add(pl);
m++;
}
public class Player {
private String name;
private int id;
public Player () {
}
Player(String val,int k) {
this.name = val;
this.id=k;}
/**
* getName
*
*/
public String getName () {
return name;
}
/**
* setName
*/
public void setName (String val,int k) {
this.name = val;
this.id=k;
}
public void displayStudentDetails(){
System.out.println("ID is "+id);
System.out.println("Name is "+name)};
i dont know how to do the search by id...i have tried many things but they didnt work....
A better solution would be to use a HashMap<Integer, String>, with the id being the key and the name being the value. Then you can search easily:
HashMap<Integer, String> map = new HashMap<Integer, String>();
map.put(1, "Robert");
map.put(2, "Jeff");
Then to search:
String name = map.get(1); // will return "Robert"
Edit: Ok, if you need more data than just name, like score, you will need to create a data type. Like:
public class Player {
private String name;
private int score;
// etc.
public Player(String name, int score) {
this.name = name;
this.score = score;
}
}
And then you can add objects of this type to the map like:
map.put(1, new Player("Robert", 10));
Ignoring the fact that you should have classes in different files without global variables at this time...
/**
* Searches the PlayerList Arraylist for a Player having the ID of the parameter passed
*/
public Player searchByID(int id) {
//Do some sort of check on id to ensure its valid?
for (int i = 0; i < PlayerList.size(); i++) {
if (PlayerList.get(i).getID() == id) {
return PlayerList.get(i);
}
}
return null;
}
ArrayList is probably the wrong data structure. If you want to retrieve the elements in id order, you want a HashMap if the ids are all regular in the sense that you can be sure of things like "ids are 1 to 10 and there are no unused ids". If the id set is sparse, you'll want a to use TreeMap or TreeSet depending on your other use cases.
If the situation where you need to get the player by ID is based exactly on how your code is adding players, then you can just do:
public Player getPlayerById(int id)
{
return PlayerList.get(id - 1);
}
Since you are assigning player ids linearly starting at 1 for the first player. If you are modifying or otherwise changing the order of players and ids then you will need to use one of the other suggestions (but if you are not doing that then this is the most optimized solution).
Note: The code above will throw an ArrayIndexOutOfBoundsException if the id does not exist in the player list, do you may want to modify the code depending on how you want to handle that.

Categories

Resources