我正在尝试按字段对对象数组进行排序,但我不断收到此错误,说明"价格/位置无法解析或不是字段",即使它们都是字段,也已声明在Realestate类中。关于"我不是一个领域"我得到了同样的错误。当我处理ArrayList时,所以我转移到简单的对象数组,我仍然得到相同的错误。我究竟做错了什么?我找到了有关将数组与Comparable和Comparator进行比较的信息,但我不知道如何将任何结果应用于排序例程。请帮忙!这些是我的文件:
档案房地产:
public class Realestate {
static String location = "";
static String description = "";
static String price = "";
// constructor
public Realestate(String loc, String desc, String prc) {
location = loc;
description = desc;
price = prc;
}
}
文件RealestateFinder:
import java.util.*;
public class RealestateFinder {
// Hold properties' info
static String[] locations = {"Miami", "Las Vegas", "Paris", "London"};
static String[] descriptions = {"1-bedroom", "2-bedrooms", "3-bedrooms", "penthouse"};
static String[] prices = {"1,000,000", "2,000,000", "3,000,000", "4,000,000"};
// Sort per field
public static void sortArray(Realestate arr[]) {
for(int x = 0; x < arr.length; ++x) {
//use array Sort
Arrays.sort(arr);
}
}
public static void main(String[] args) {
int numProperties = 4;
//Create new Realestate object newProperty
Realestate[] newProperty = new Realestate[numProperties];
// Initialize array of objects Realestate[] newProperty using arrays from top
for(int x = 0; x < newProperty.length; ++x) {
newProperty[x] = new Realestate(locations[x], descriptions[x], prices[x]); // constructor
}
//Get user's input
//...
while(true) {
if(holdUserInput == 1) {
//sort per price
sortArray(newProperty.price);//price cannot be resolved or is not a field
break;
}
else if(holdUserInput == 2) {
// sort per location
sortArray(newProperty.location);//location cannot be resolved or is not a field
break;
}
else {
System.out.println("Program Ended \n");
break;
}// end else statement
}// end while loop
}// end main()
}// end class RealestateFinder
答案 0 :(得分:2)
首先,您可能不会对3个字段使用静态,static
表示它与特定实例无关,而不是您想要的
然后使用List
更容易排序:
int numProperties = 4;
List<Realestate> list = new ArrayList<>();
for (int x = 0; x < numProperties; ++x) {
list.add(new Realestate(locations[x], descriptions[x], prices[x]));
}
然后,使用现有的排序方法更快更容易使用:
while (true) {
if (holdUserInput == 1) {
list.sort(Comparator.comparing(Realestate::getPrice));
break;
} else if (holdUserInput == 2) {
list.sort(Comparator.comparing(Realestate::getLocation));
break;
} else if (holdUserInput == 2) {
list.sort(Comparator.comparing(Realestate::getDescription));
break;
} else {
System.out.println("Program Ended \n");
break;
}// end else statement
}
最后,因为没有理由使用while(true)
和break
,所以最好更好地使用switch
:
switch (holdUserInput) {
case 1:
list.sort(Comparator.comparing(Realestate::getPrice));
break;
case 2:
list.sort(Comparator.comparing(Realestate::getLocation));
break;
case 3:
list.sort(Comparator.comparing(Realestate::getDescription));
break;
default:
System.out.println("Program Ended \n");
break;
}