gpt4 book ai didi

java - 如何按字符串对象的升序对对象数组进行排序?

转载 作者:行者123 更新时间:2023-12-02 01:05:17 25 4
gpt4 key购买 nike

我必须接受用户输入(int id、字符串标题、字符串文件夹、int 页面)。我必须按字符串标题(字典)的升序排列输出。我已经编写了代码,但输出却截然不同。

package zzz;
import java.util.Scanner;
import java.util.Arrays;
import java.util.Collections;

class Book{
int id;
String title;
String folder;
int pages;
}


public class practice {

public static void main(String[] args)throws Exception {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
Book b1 = new Book();
Book b2 = new Book();
Book b3 = new Book();
Book b[]= {b1,b2,b3};
for(int i=0;i<b.length;i++) {
b[i].id=sc.nextInt();
sc.nextLine();
b[i].title=sc.next();
sc.nextLine();
b[i].folder=sc.next();
b[i].pages=sc.nextInt();
}
Book temp = null;
for(int i=0;i<b.length;i++) {
for(int j=0;j<b.length-1-i;j++) {
if(b[i].title.compareTo(b[j].title)<0) {
temp =b[j];
b[j]=b[j+1];
b[j+1]=temp;
}}
}
for(int i=0;i<b.length;i++) {
System.out.println(b[i].id+" "+b[i].title+" "+b[i].folder+" "+b[i].pages);
}

}}

enter image description here

最佳答案

我会删除开头的类并在 main 方法之后添加该类,如下所示:

static class Book implements Comparable<Book>{
int id;
String title;
String folder;
int pages;

@Override
public int compareTo(Book other) {
//If this is backword then switch it to -> other.title.compareTo(this.title);
return this.title.compareTo(other.title);
}
}

与:Implements Comparable to get alphabetical sort with Strings相同

然后你可以获取书籍数组并使用Arrays.sort(book_arr);

给你:

package zzz;
import java.util.Scanner;
import java.util.Arrays;
import java.util.Collections;


public class practice {

public static void main(String[] args)throws Exception {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
Book b1 = new Book();
Book b2 = new Book();
Book b3 = new Book();
Book b[]= {b1,b2,b3};
for(int i=0;i<b.length;i++) {
b[i].id=sc.nextInt();
sc.nextLine();
b[i].title=sc.next();
sc.nextLine();
b[i].folder=sc.next();
b[i].pages=sc.nextInt();
}

//Sort!
Arrays.sort(b);

for(int i=0;i<b.length;i++) {
System.out.println(b[i].id+" "+b[i].title+" "+b[i].folder+" "+b[i].pages);
}

}
static class Book implements Comparable<Book>{
int id;
String title;
String folder;
int pages;

@Override
public int compareTo(Book other) {
return this.title.compareTo(other.title);
}
}
}

It works!

关于java - 如何按字符串对象的升序对对象数组进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60128167/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com