N
N
Nikita Badyl2016-05-11 01:50:02
Java
Nikita Badyl, 2016-05-11 01:50:02

What is the correct way to sort an array of objects?

Please tell me what I'm doing wrong, I can't figure it out. You need to sort the strings by length.

package lesson6;


import java.util.Scanner;

public class Student {
  String name;
  
  
  
  
public static Student[] createMass(int n){
  Scanner sc1=new Scanner(System.in);
  System.out.println("Введите количество строк");
  if(sc1.hasNextInt()){
  n=sc1.nextInt();	
  }
  Student[] mass = new Student[n];
  for(int i = 0;i<mass.length;i++){
    mass[i] = new Student();
    mass[i].create();
    
  }
  return mass;
}

public   void create(){
  Scanner sc = new Scanner(System.in);
  System.out.println(" Введите имя ");
  if(sc.hasNextLine()){	
  name = sc.nextLine();
  if(name.endsWith("end")){
    name=" ";
  }
  }
  }	
  
  
  
  
public static void showMas(Student[]mass){
  for(int i=0;i<mass.length;i++){
    System.out.print("["+i+"]");
    mass[i].show();
  }
  
}
public void show(){
  System.out.println(name);
}
public void show1(Student[]mass){
  for(int i=0;i<mass.length;i++){
    System.out.print("["+i+"]");
  }
}
public static void sartirovka(Student mass[]){
  for(int j = 0; j<mass.length;j++){
    for( int i = j+1;i<mass.length;i++);{
      if( mass[i].compareTo( mass[j])<0){
        Student t = mass[j];
        mass[j] = mass[i];
        mass[i] = t;
        
        
      }
    }
  System.out.println(mass[j]);
      }
    }

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexander Kosarev, 2016-05-11
@nibbit

Stream.of(mass)
        .sorted((m1, m2) -> m1.name.length() < m2.name.length() ? -1 : 1)
        .toArray();

If I understand correctly that you need to sort the array of students by the length of the name.

I
ifqthenp, 2016-05-11
@ifqthenp

This problem is solved with the help of interfaces.
But, judging by how sloppy and confusing the code is, you'd better start learning Java from the very basics.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question