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;
}
}
Related
I am trying to call the array variables in the reference class, try to sort them using a user-defined method and call the method onto the case statement that will be invoked if the user chooses a particular number. I wanted to provide the user the option what attribute of a student will be sorted (i.e. name, course...) and show the sorted one dimensional array called in the case statements and invoked through the main method.
Here's the variables in the Reference class:
class RecordReference {
private int idNumber;
private String firstName = "";
private String middleName = "";
private String lastName = "";
private int age;
private String yearLevel;
private String course = "";
private double gwa;
public RecordReference(int i, String f, String m, String l, int a, String y, String c, double g) {
idNumber = i;
firstName = f;
middleName = m;
lastName = l;
age = a;
yearLevel = y;
course = c;
gwa = g;
}
public int getIdNumber() {
return idNumber;
}
public String getFirstName() {
return firstName;
}
public String getMiddleName() {
return middleName;
}
public String getLastName() {
return lastName;
}
public int getAge() {
return age;
}
public String getYearLevel() {
return yearLevel;
}
public String getCourse() {
return course;
}
public double getGwa() {
return gwa;
}
public void setIdNumber(int idnumber) {
idNumber = idnumber;
}
public void setFirstName(String fName) {
firstName = fName;
}
public void setMiddleName(String mName) {
middleName= mName;
}
public void setLastNameName(String lName) {
lastName= lName;
}
public void setAge(int a) {
age = a;
}
public void setYearLevel(String yLevel) {
yearLevel = yLevel;
}
public void setCourse(String c) {
course = c;
}
public void setGwa(int gwa) {
gwa = gwa;
}
public String toString() {
return String.valueOf(System.out.printf("%-15s%-15s%-15d%-15d%n",
firstName, course , yearLevel ,gwa));
}
} // end of class
And I am trying to call it in this sort method, but I don't know how to reference it.
public static void sortFirstNameArray(String[] f){
for (int i = 0; i < f.length - 1; i++) {
for (int j = i + 1; j < f.length; j++) {
if (f[i].compareToIgnoreCase(f[j]) > 0) {
String temp = f[i];
f[i] = f[j];
f[j] = temp;
}
}
}
}
After the sorting is successfully done, I'll call it in a switch case statements that will be invoked once the user chooses a particular number. This part has 5 case statements (Name, Age, Course, General Weighted Average and the option to sort it all - I plan to add more student attributes if this works)
(I don't know if I should store this in another method and call it in the main method or just put it in the main method like that)
public RecordReference Process(RecordReference[] f, RecordReference[] a) {
// for loop?
for (int x = 0; x < f.length; x++) {
switch (choice) {
case 1:
System.out.println("Sorted array of first name: ");
sortFirstNameArray(f[x].getFirstName());
System.out.printf("%-15s%n", Arrays.toString(f));
break;
case 2:
System.out.println("Sorted array of age: ");
// invokes the age method
sortAgeArray(a[x].getAge());
System.out.printf("%-15s%n", Arrays.toString(a));
break;
}
}
}
If it is in another method, what param do I include when I call it in the main method?
I tried this but it doesn't work, I don't know what to do
System.out.print("Please choose what student attribute you want to
sort :");
choice = keyboard.nextInt();
// calling the process method here, but I receive syntax error
Process(f,a); // Here, I want to pass the sorted values back into the array but I get an error.
If you can help me out that would be great. Thank you in advance.
I'm just a first year student and I am eager to learn in solving this error.
It's good to see that you have attempted the problem yourself and corrected your question to make it clearer, because of that I am willing to help out.
I have tried to keep the solution to the problem as close to your solution as possible, so that you are able to understand it. There may be better ways of solving this problem but that is not the focus here.
First of all, let's create a class named BubbleSorter that will hold methods for sorting:
public class BubbleSorter
{
//Explicitly provide an empty constructor for good practice.
public BubbleSorter(){}
//Method that accepts a variable of type RecordReference[], sorts the
//Array based on the firstName variable within each RecordReference
//and returns a sorted RecordReference[].
public RecordReference[] SortByFirstName(RecordReference[] recordReferencesList)
{
for (int i = 0; i < recordReferencesList.length - 1; i++) {
for (int j = i + 1; j < recordReferencesList.length; j++) {
if (recordReferencesList[i].getFirstName().compareToIgnoreCase
(recordReferencesList[j].getFirstName()) > 0) {
RecordReference temp = recordReferencesList[i];
recordReferencesList[i] = recordReferencesList[j];
recordReferencesList[j] = temp;
}
}
}
return recordReferencesList;
}
}
That gives us a class that we can instantiate, where methods can be added to be used for sorting. I have added one of those methods which takes a RecordReference[] as a parameter and sorts the RecordReference[] based on the firstName class variable within each RecordReference. You will need to add more of your own methods for sorting other class variables.
Now for the main class:
class Main {
public static void main(String[] args) {
//Get a mock array from the GetMockArray() function.
RecordReference[] refArray = GetMockArray();
//Instantiate an instance of BubbleSorter.
BubbleSorter sorter = new BubbleSorter();
//Invoke the SortByFirstName method contained within the BubbleSorter
//and store the sorted array in a variable of type RecordReference[] named
//sortedResult.
RecordReference[] sortedResult = sorter.SortByFirstName(refArray);
//Print out the results in the sorted array to check if they are in the correct
//order.
//This for loop is not required and is just so that we can see within the
//console what order the objects in the sortedResult are in.
for(int i = 0; i < sortedResult.length; i++)
{
System.out.println(sortedResult[i].getFirstName());
}
}
public static RecordReference[] GetMockArray()
{
//Instantiate a few RecordReferences with a different parameter for
//the firstName in each reference.
RecordReference ref1 = new RecordReference(0, "Ada", "Test", "Test", 22, "First",
"Computer Science", 1.0f);
RecordReference ref2 = new RecordReference(0, "Bob", "Test", "Test", 22, "First",
"Computer Science", 1.0f);
RecordReference ref3 = new RecordReference(0, "David", "Test", "Test", 22,
"First", "Computer Science", 1.0f);
//Create a variable of type RecordReference[] and add the RecordReferences
//Instantiated above in the wrong order alphabetically (Based on their firstName)
//class variables.
RecordReference[] refArray = {
ref2, ref3, ref1
};
return refArray;
}
}
In the main class I have provided verbose comments to explain exactly what is happening. One thing I would like to point out is that I have added a method named GetMockArray(). This is just in place to provide a RecordReference[] for testing and you probably want to do that somewhere else of your choosing.
If anything is not clear or you need some more assistance then just comment on this answer and I will try to help you further.
Thanks.
I have a class called Person, where I have a constructor, getters, and setters for three variables: name, age, and height. I also have implemented a Selection sort method in this class to sort the ages of people. Then I have created an array with ten people and I have given them different names, ages, and heights, but I have not gotten to use the Selection sort method to sort the ages of people. I would like to know if you could help me to know what I am doing wrong and why I have not gotten to use the method within my array.
I would also like to know if there is a smarter (less manual) way to implement an array of the type I would like to (with name, age, and height), because I will add more people, like 20 people, and that is going to demand some extra work that I guess I could save with some better method. I know how to do it with an array list, but I would like to know with an array if that is possible, or reasonable.
//Class Person
public class Person {
private String name;
private int height;
private int age;
public void Person (String name, int height, int age){
this.name = name;
this.height = height;
this.age = age;
}
public String getName (){
return name;
}
public int getHeight (){
return height;
}
public int getAge (){
return age;
}
public void setName (String name) {
this.name = name;
}
public void setHeight (int height) {
this.height=height;
}
public void setAge (int age) {
this.age=age;
}
public int[] selectionSort (int[] age){
int i, j, minValue, minIndex, temp =0;
for (i = 0; i<age.length; i++) {
minValue = age[i];
minIndex = i;
for (j=i; j<age.length; j++) {
if (age[i]<minValue){
minValue = age [j];
minIndex = j;
}
}
if (minValue<age[i]){
temp=age[i];
age[i]=age[minIndex];
age[minIndex]=temp;
}
}
return age;
}
}
//Array implementation
public class Main {
public static void main(String[] args) {
Person [] persons = new Person [3];
persons [0] = new Person ();
persons [0].setName("Josef");
persons [0].setHeight(170);
persons [0].setAge(30);
persons [1] = new Person ();
persons [1].setName("Marie");
persons [1].setHeight(160);
persons [1].setAge(35);
persons [2] = new Person ();
persons [2].setName("Karel");
persons [2].setHeight(180);
persons [2].setAge(40);
for (int i=0; i<persons.length; i++){
System.out.println("Jméno: " + persons[i].getName()+ ", věk: " + persons[i].getAge() + ", vyška: " + persons[i].getHeight());
}
//My main problem is here
for (int i = 0; i<persons.length; i++){
System.out.println(persons[i].selectionSort());
}
}
}
There are several problems with your code, you have to study it online and clear your concepts. However, I am going to explain a bit:
System.out.println(persons[i].selectionSort());
Now, you have created this method selectionSort() and you can use this on an object of type Person but it is expecting a parameter of type int[], which you are not providing.
It is a logical error, selectionSort doesn't work like that you can't call this method on every index of array. Its his job to sort the array at once. So, you have to pass the whole persons[] array and the rest will be done by selectionSort()
public int[] selectionSort (int[] age)
You are using int age[], you can't do this because you don't have an array of type int, what you have is array of type Person each object of type Person has an attribute age and you can access this by dot operator.
Working Code:
public class Person
{
public static Person [] persons = new Person [3]; // so that every method can access this array
private String name;
private int height;
private int age;
public void Person (String name, int height, int age){
this.name = name;
this.height = height;
this.age = age;
}
public String getName (){
return name;
}
public int getHeight (){
return height;
}
public int getAge (){
return age;
}
public void setName (String name) {
this.name = name;
}
public void setHeight (int height) {
this.height=height;
}
public void setAge (int age) {
this.age=age;
}
public static void selectionSort(Person persons[])
{
int smallest;
for(int i = 0; i < persons.length; i++)
{
smallest=i;
for(int index = i+1; index<persons.length; index++)
if(persons[index].age<persons[smallest].age)
smallest=index;
swap(i,smallest);
}
}
public static void swap(int frst, int scnd)
{
Person temporary = persons[frst];
persons[frst] = persons[scnd];
persons[scnd] = temporary;
}
public static void main(String[] args)
{
persons [0] = new Person ();
persons [0].setName("Josef");
persons [0].setHeight(170);
persons [0].setAge(35);
persons [1] = new Person ();
persons [1].setName("Marie");
persons [1].setHeight(160);
persons [1].setAge(31);
persons [2] = new Person ();
persons [2].setName("Karel");
persons [2].setHeight(180);
persons [2].setAge(40);
for (int i=0; i<persons.length; i++){
System.out.println("Jmeno: " + persons[i].getName()+ ", vek: " + persons[i].getAge() + ", vyska: " + persons[i].getHeight());
}
selectionSort(persons);
for (int i = 0; i<persons.length; i++){
System.out.println(persons[i].age);
}
}
}
NOTE: I have merged code in same class Person, but you can divide them into Main and Person always. It is recommended that if you divide the code then include selectionSort() in Main.
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());
}
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
}
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.