Answer the question
In order to leave comments, you need to log in
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
Stream.of(mass)
.sorted((m1, m2) -> m1.name.length() < m2.name.length() ? -1 : 1)
.toArray();
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question