For example: I want to input the name of 3 students and their respective height. How can I make the relation that String Student name #1 correlates with Integer Student Height #1, so in this way I can reveal in a statement who is the tallest student out of the 3 by outputting his/her name based on the g tallest out of the 3 given heights. In small words, how can I relate String[0] to Integer[0].
CodePudding user response:
You can create a Student class and add name and height in it. Then you can create a Student[] array object. Please check the code below
public class ArraysDemo {
public static void main(String[] args) {
Student[] students = new Student[3];
students[0] = new Student("AAAA", 168);
students[1] = new Student("BBBB", 172);
students[2] = new Student("CCCC", 180);
}
}
class Student {
String name;
int heightInInch;
public Student(String name, int heightInInch) {
this.name = name;
this.heightInInch = heightInInch;
}
}
CodePudding user response:
You can just use the index. When the data is created, you're going to enter studentName[0] and studentHeight[0] at the same time, so the index (0) will be how you can get both.
But you're doing it "the wrong way", in my opinion. Why not make a Student object that has the property of name and property of height. Then toss each student into a List. Or if you want to go quickly to a specific student, toss each student into a Map.
CodePudding user response:
Can there be duplicate student names? If not I would recommend you use an implementation of the Map interface. A Map
allows you to store key - value pairs. So you can use the student name as the key and the height as the value, and then figure out how you want to find the tallest one.
If there can be duplicate student names you could create a basic class to store this info. Create an object for each student and store them in an array/list and figure out you want to sort it.
public class Student {
private String name;
private int height;
public Student(String name, int height) {
this.name = name;
this.height = height;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getHeight() {
return height;
}
public void setHeight(int height) {
this.height = height;
}
}