gpt4 book ai didi

java - Java 中的数组排序 soicanpost

转载 作者:行者123 更新时间:2023-11-30 01:58:49 25 4
gpt4 key购买 nike

我的问题是如何对 arrayofnames 和 arrayofdownloads 进行排序,以便它们按升序排列,并且每个名称与其相应的下载数量相匹配。我已经尝试了 4 个小时,但我似乎无法理解它

谢谢

    import java.util.*;
import java.util.stream.*;

public class short6
{
public static void main(String[] args)
{
String[] arrayofnames = new String[4];
int[] arrayofdownloads = new int[4];

printmessage(arrayofnames, arrayofdownloads);
details(arrayofnames, arrayofdownloads);
System.exit(0);
}

public static void printmessage(String[] arrayofnames, int[] arrayofdownloads)
{
Scanner scanner = new Scanner(System.in);
int totalDownloads = 0;

for (int i = 0; i < arrayofnames.length; i++)
{
System.out.println("What is track " + (i + 1));
arrayofnames[i] = scanner.nextLine();
System.out.println("How many thousands of times has it been downloaded? ");
arrayofdownloads[i] = Integer.parseInt(scanner.nextLine());
}

Arrays.sort(arrayofnames);
Arrays.sort(arrayofdownloads);

System.out.println("The track downloaded the most is " + arrayofdownloads[0]+".");
}

public static void details(String[] arrayofnames, int[] arrayofdownloads)
{
int totaldownloads = IntStream.of(arrayofdownloads).sum();
System.out.println("The track downloaded the most is " + arrayofdownloads[0]+".");
System.out.println("The total number of downloads of these 4 tracks was " + totaldownloads * 1000 +".");

System.out.println("\nThe details of the downloads are");

for (int i = 1; i < arrayofnames.length; i++)
{
System.out.println(arrayofnames[i]);
System.out.println((arrayofdownloads[i]));
}
}
}

最佳答案

我将开始创建一个包含歌曲名称和下载次数的歌曲(例如)类:

public class Song {

private String name;

private int downloads;

public Song(String name, int downloads) {
this.name = name;
this.downloads = downloads;
}

public String getName() {
return this.name;
}

public int getDownloads() {
return this.downloads;
}

}

然后,创建歌曲数组:

Song[] arrayOfSongs = new Song[4];

并从输入加载它:

arrayOfSongs[i] = new Song(scanner.nextLine(), Integer.parseInt(scanner.nextLine()));

现在您只需使用比较器对其进行排序:

Arrays.sort(arrayOfSongs, new Comparator<Song> () {
public int compare(Song o1, Song o2) {
// Sorting by name
return o1.getName().compareTo(o2.getName());
}

});

或者,正如 @Benoit 在评论中所说,这样会更容易(Java 8 或更高版本):

Arrays.sort(arrayOfSongs, Comparator.comparing(Song::getName));

大功告成,只需打印对象(toString 方法在这里会很有帮助),您就可以对信息进行排序。

编辑:要读取编写问题的输入,您只需将值存储在变量中,例如

System.out.println("What is track " + (i + 1));
String songName = scanner.nextLine();
System.out.println("How many thousands of times has it been downloaded? ");
int songDownloads = Integer.parseInt(scanner.nextLine());
arrayOfSongs[i] = new Song(songName, songDownloads);

或者您可以在 Song 类中实现 setter 方法并创建一个不带参数的构造函数,这样您就可以在读取值时设置它们。

关于java - Java 中的数组排序 soicanpost,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53538745/

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