Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 12 months ago.
Improve this question
I have seen ArrayList examples but I want to know how to add objects guitar and ukulele to array i.
And also, how to return the object which has the highest number of strings?
public class Demo{
public static void main(String[] args) {
Instrument guitar = new Instrument("Guitar", 6);
Instrument ukulele = new Instrument("Ukulele", 4);
Instrument i[] = new Instrument[2];
// Adding objects guitar and ukulele to class array i
// Returning object with maximum number of strings
}
}
class Instrument{
private String name;
private int numOfStrings;
public Instrument(String name, int numOfStrings){
this.name = name;
this.numOfStrings = numOfStrings;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getStrings() {
return numOfStrings;
}
public void setStrings(int numOfStrings) {
this.numOfStrings = numOfStrings;
}
}
I think you are asking for this:
// Adding objects guitar and ukulele to class array i
i[0] = guitar;
i[1] = ukulele;
// Returning object with maximum number of strings
int max = i[0].getStrings();
for (Instrument inst : i) {
if(inst.getStrings() > max)
max = inst.getStrings();
}
System.out.println(max);
First of all assign the objects to the array. Then iterate them keeping track of the highest value. I suggest you to study deeper the basics of Java to solve this simple problems :)
Here's some code showing the implementation you were asking about, hope it helps (I'd suggest looking more at object and array fundamentals)
public class Demo{
public static void main(String[] args) {
Instrument guitar = new Instrument("Guitar", 6);
Instrument ukulele = new Instrument("Ukulele", 4);
Instrument i[] = new Instrument[2];
// Since you declared your array with empty elements, you'll have to get the current element and set the new vals manually (or use iteration)
i[0] = guitar;
i[1] = ukulele;
//Alternatively, you could initialise your array with the values already set like this
Instrument arr[] = new Instrument[] {guitar, ukulele};
// Returning object with maximum number of strings
Instrument highestStrung = getHighestStrungInstrument(arr);
System.out.println("Highest: " + highestStrung.getName());
}
private static Instrument getHighestStrungInstrument(Instrument[] arr){
//Var to hold current highest strings
int highestStrings = 0;
//Var to hold the obj with the current highest strings
Instrument currentHighest = null;
//loop through all the objects in the array
for(Instrument inst : arr)
//compare the current instrument's strings with that of the var's val
if(inst.getStrings() > highestStrings){
//set the new highest
currentHighest = inst;
highestStrings = inst.getStrings();
}
//Return the highest obj (Keep in mind that the val could be null)
return currentHighest;
}
}
class Instrument{
private String name;
private int numOfStrings;
public Instrument(String name, int numOfStrings){
this.name = name;
this.numOfStrings = numOfStrings;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getStrings() {
return numOfStrings;
}
public void setStrings(int numOfStrings) {
this.numOfStrings = numOfStrings;
}
}
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
}
This question already has answers here:
How do I use Comparator to define a custom sort order?
(9 answers)
Closed 7 years ago.
I am struggling sorting an array in order of an object's property. I know how to sort numbers in order, but I can't figure out how to do it with an object. For example, let's say object A has a position attribute of 1 and object B has a position attribute of 2. These objects are in an array. How could I sort them according to this property?
Thanks
You have something like:
public class ExampleObject {
public int position;
}
Then, simply use a Comparator.
public static void main(String args[]) {
//example numbers
final Random r = new Random();
final List<ExampleObject> arrList = new ArrayList<>(100);
for (int i = 0; i < 100; i++) {
ExampleObject obj = new ExampleObject();
obj.position = r.nextInt(1000);
arrList.add(obj);
}
//comparator (as a lambda)
Collections.sort(arrList, (a, b) -> {
return a.position - b.position;
});
//output result
for (ExampleObject obj : arrList) {
System.out.println(obj.position);
}
}
Also, in case you must sort an array and not a List, you can use Arrays.sort() with a Comparator like this as well.
You can compare by implementing Comparable interface in your class like below.
public class Applcation {
public static void main(String[] args) {
A ary[] = {new A("D", 1),new A("C", 7),new A("K", 4),new A("L", 8),new A("S", 3)};
Arrays.sort(ary);
for (A a : ary) {
System.out.println(a.id+" - "+a.name);
}
}
}
class A implements Comparable<A>{
String name;
int id;
public A(String name, int id) {
this.name = name;
this.id = id;
}
#Override
public int compareTo(A a) {
return this.id-a.id;
}
}
Or as an alternative you can use java 8 streams to sort your array without implementing Comparable :
Arrays.stream(ary).sorted((a1,a2)->Integer.compare(a1.id, a2.id)).forEach(e->System.out.println(e.id+" - "+e.name));
Out-put :
1 - D
3 - S
4 - K
7 - C
8 - L
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;
}
}
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.