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.
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 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
}
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;
}
}
i already have the athelete class and i just dont know how to go about the rest of the problem ive been trying to do things that havent work at all but heres what i have for now. im still a beginner this is my first semester taking java so i may not understand some of the things you guys will add so if u can please explain.
This is what they are asking for me to do.
Add a static method to the class which takes an array of Athletes as its argument, and returns the total number of medals won by all athletes stored in the array. test in method.
package homework;
import java.util.Arrays;
public class Athlete {
private String name; // the name of the athlete
private String sport; // the sport the athlete does
private int numMedals; // the number of medals that the athlete has won
// constructor
public Athlete(String n, String s, int num) {
name = n;
sport = s;
numMedals = num;
}
// getters and setters for all instance variables
// (also called accessors and mutators)
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSport() {
return sport;
}
public void setSport(String sport) {
this.sport = sport;
}
public int getNumMedals() {
return numMedals;
}
public void setNumMedals(int numMedals) {
this.numMedals = numMedals;
}
/* Returns a String with information about the athlete.
*/
public String toString() {
return name + " does " + sport + " and has won " + numMedals + " medal(s).";
}
public static void AthMedals(int[][]numMedals){
for(int i = 0; i < numMedals.length;i++){
int total = 0;
for(int j = 0; j < numMedals.length; i++);
total = numMedals.getNumMedals();
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Athlete SA = new Athlete("Socrates","Baseball",5);
Athlete CC = new Athlete("Cesar","Baseball",3);
Athlete JA = new Athlete("Juan","Soccer",2);
System.out.println(SA);
System.out.println(CC);
System.out.println(JA);
System.out.println("SA has " +SA.getNumMedals()+ " medals.");
}
}
}
The assignment is to write a method like
public static int sumOfAllMedals(Athlete[] all)
which returns all[0].numMedals + all[1].numMedals + ... + all[n].numMedals.
I assume AthMedals is your attempt at doing this, but it's in fact only consuming processing power while not doing anything.
I'm not gonna do your homework for you, but here's a hint:
public static int sumOfAllMedals(Athlete[] all)
{
int total = 0;
// For every Athlete in `all`, add the number of medals (s)he's won
// Should be four lines at most ;)
return total;
}
The static method have to iterate the array and add each medals to a final return variable.
static public int totalMedals(Athlete[] athelte) {
int totalMedals = 0;
for(int i=0;i<athelte.length;i++) {
totalMedals += athelte[i].numMedals;
}
return totalMeadls;
}
Can anyone tell me where im going wrong I have three files Person.java Queue.java & Cinema.java, ive managed to do queues without objects Person.java but. I am having trouble implementing with objects.
Heres my Queue.java
public class Queue
{
private Person[] person = new Person[10];
private int rear;
public Queue()
{
rear = 0;
}
public boolean isEmpty()
{
return rear == 0;
}
public String remove() //remove String element
{
String result = person[0].toString(); //shuffle String elements
rear--;
for (int i = 0; i < rear ; i++)
{
person[i] = person[i + 1];
}
return result;
}
public void add(Person x) //add String element
{
if (rear == person.length)
{
resize();
}
person[rear] = x;
rear++;
}
private void resize()
{
Person[] temp = new Person[person.length * 2]; //resize String array
for (int i = 0; i < person.length; i++)
{
temp[i] = person[i];
}
person = temp;
}
}
Then heres Person.java (Object).
public class Person
{
private String name;
private int age = 0;
public Person(String name1, int age1)
{
this.name = name1;
this.age = age1;
}
}
And heres the main java file Cinema.java
import java.util.*;
public class Cinema {
public static void main (String[] args)
{
Queue q = new Queue();
Scanner k = new Scanner(System.in);
System.out.print("Enter name: ");
String name = k.nextLine();
System.out.print("Enter Age : ");
int age = k.nextInt();
q.add(name);
System.out.println(name + " joined queue");
}
}
Basically I want a person to join the queue with a name and age and the first person goes to buy the ticket and the age is checked. I can do the check bit its just getting it to read with objects.
Thanks
So I see two issues up here :
The Queue class seems to be implemented as a Stack rather than a Queue. I would suggest, Google about what queues are .
In your main method
String name = k.nextLine();
System.out.print("Enter Age : ");
int age = k.nextInt();
q.add(name);
Here, add method requires a person object as its parameter rather than a String object.
The code should be like :
String name = k.nextLine();
System.out.print("Enter Age : ");
int age = k.nextInt();
Person p1 = new Person(name,age);
q.add(p1);
Hope this helps.
EDIT!!!:
For your question in the comment. If you want to return age of the people in the Queue. You first would have to make two getter methods. One inside the Person class & other in the Queue class:
In person class:
public int getAge()
{
return age;
}
In Queue class:
public Person[] getPerson()
{
return person;
}
After writing these functions down. You can have the ages of people in the queue as :
Person[] p = q.getPerson(); // q is the Queue object
for(int i=0;i<p.length;i++)
{
if(p[i]!=0)
{
System.out.println(p[i].getAge());
}
}
Hope this helps. if this helps you reach the solution of your problem, do upvote and select the answer as correct one.