[英]Sending an array from one class to another and sorting
我需要一些帮助。 所以,最近我开始在 Java 中研究一些更复杂的东西,我有一个任务来编写一个程序,该程序将人们和他们拥有的钱按从最大到最小的降序排列,但是带有人名的数组在一个 class 中,金额在另一个 class 中,我必须将它们发送到第三个 class 然后对其进行排序。 我试图让它工作,甚至问我的老师,但即使他为此编写的代码也不起作用。 这就是我到目前为止所拥有的。
package classes;
public class Class {
public static void main(String[] args) {
String[]Name = {"Frodo","Princess Leia","Sansa Stark","Harry Potter","Spiderman"};
Class3 send = new Class3();
send.doesntmatter(Name);
}
}
第二个 class 有钱。
package classes;
class Class2 {
public static void main (String[]args) {
int[]Money = {3000,400000,50000,100000,25};
Class3 send = new Class3();
send.doesntmatter(Money);
}
}
第三个 class 全部排序。
package classes;
class Class3 {
public void doesntmatter(String[]Name,int[]Money) {
for(int first = 0; first < 4; first++){
int most = first;
for(int current = first + 1; current < 4; current++){
if (Money[current] > Money[most]){
most = current;
}
int temp = Money[most];
Money[most] = Money[first];
Money[first] = temp;
String tempString = Name[most];
Name[most] = Name[first];
Name[first] = tempString;
}
for (int i = 0; i < 4; i++){
System.out.println(Name[i]);
System.out.println(Money[i]);
}
}
}
}
我知道如何对它们进行排序,但是将 arrays 发送到另一个 class 时遇到问题。 有人可以帮忙吗? 我希望你明白我的问题是什么。
你需要让无关紧要的 function 返回你想要的数组:
public int[] doesntmatter(String[]Name,int[]Money) {
for(int first = 0; first < 4; first++){
int most = first;
for(int current = first + 1; current < 4; current++){
if (Money[current] > Money[most]){
most = current;
}
int temp = Money[most];
Money[most] = Money[first];
Money[first] = temp;
String tempString = Name[most];
Name[most] = Name[first];
Name[first] = tempString;
}
for (int i = 0; i < 4; i++){
System.out.println(Name[i]);
System.out.println(Money[i]);
}
}
return Money;
}
这意味着无关紧要的 function 将制作 Money 数组的本地副本,对其进行排序并返回。 然后在 Class 您需要更改此代码:
Money = send.doesntMatter(Money);
最后一行将使用未排序的数组调用dontMatter。 function 将创建一个本地副本,对该本地副本进行排序,返回,然后将 function 返回的该本地副本分配给 Money 变量。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.