Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /////////////////// Main Class //////////////////////////////
- public class PersonView {
- public static void main(String[] args) {
- Person[] persons = new Person[5];
- initPersonsArray(persons);
- printPersons(persons);
- sort(persons, 1);
- printPersons(persons);
- sort(persons, 0);
- printPersons(persons);
- }
- private static void initPersonsArray(Person[] pArray) {
- for(int i = 0; i < pArray.length; i++) {
- pArray[i] = new Person();
- pArray[i].setName("Person"+i);
- pArray[i].setHeight(Math.random()*20+175);
- pArray[i].setWeight(Math.random()*20+80);
- }
- }
- private static void printPersons(Person[] pArray) {
- for(int i = 0; i < pArray.length; i++) {
- pArray[i].show();
- }
- System.out.println();
- }
- private static void sort(Person[] p, int by) {
- if(by == 1) {
- sortByHeight(p);
- }else {
- sortByWeight(p);
- }
- }
- private static void sortByHeight(Person[] pArray) {
- Person pUtil;
- for(int i = 1; i < pArray.length; i += 1) {
- int j = i;
- while(j > 0) {
- if(pArray[j].getHeight() < pArray[j-1].getHeight()) {
- pUtil = pArray[j];
- pArray[j] = pArray[j-1];
- pArray[j-1] = pUtil;
- }
- j -= 1;
- }
- }
- }
- private static void sortByWeight(Person[] pArray) {
- Person pUtil;
- for(int i = 1; i < pArray.length; i += 1) {
- int j = i;
- while(j > 0) {
- if(pArray[j].getWeight() < pArray[j-1].getWeight()) {
- pUtil = pArray[j];
- pArray[j] = pArray[j-1];
- pArray[j-1] = pUtil;
- }
- j -= 1;
- }
- }
- }
- }
- ////////////////////////////////// Person Class //////////////////////////////////
- public class Person {
- // Declaring the class properties
- String name;
- double height;
- double weight;
- // Implementing the methods
- public String getName() {
- return name;
- }
- public boolean setName(String name) {
- this.name = name;
- return true;
- }
- public double getHeight() {
- return height;
- }
- public boolean setHeight(double height) {
- if(height <= 0) {
- System.out.println("Height must be greater then 0!");
- return false;
- }
- this.height = height;
- return true;
- }
- public double getWeight() {
- return weight;
- }
- public boolean setWeight(double weight) {
- if(weight <= 0) {
- System.out.println("Weight must be greater then 0!");
- return false;
- }
- this.weight = weight;
- return true;
- }
- public void show() {
- System.out.printf("The person's name is %s; He's height is %f and he's weight is %f\n", name, height, weight);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement