在 Java 中按字段对对象数组进行排序:"variable cannot be resolved or is not a field"



我正在尝试按字段对对象数组进行排序,但我不断收到此错误,说"价格/位置无法解析或不是字段",即使它们都是字段,在类 Realestate 中声明。当我处理 ArrayList 时,我也遇到了关于"不是字段"的相同错误,所以我转向简单的对象数组,但我仍然收到同样的错误。我做错了什么?我找到了有关将数组与可比较器和比较器进行比较的信息,但我不了解如何将任何结果应用于排序例程。请帮忙!这些是我的文件:

文件不动产:

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;
}
}

文件房地产查找器:

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

首先,您不能对 3 个字段使用 static,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;
}

相关内容

最新更新