java 如何按价格和名称对我的商品进行排序?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4981924/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I sort my items by both price and name?
提问by allencoded
So I have a question on what to do next. I am working on this program and the requirements are.
所以我有一个关于下一步该怎么做的问题。我正在研究这个程序,要求是。
Wings Coffee Shop
翅膀咖啡店
A local coffee shop sells a variety of different items shown below to their customers. You are asked to write a Java application that can be used to keep track of these items. Additionally, this program provides a way to print out a listing of the items.
当地一家咖啡店向客户出售如下所示的各种不同商品。您需要编写一个 Java 应用程序来跟踪这些项目。此外,该程序还提供了一种打印项目列表的方法。
Item Name Price
Coffee .00
Water .00
Milk .50
Bagel .25
Donut import java.util.Scanner;
public class CoffeeDriver {
//main method
public static void main (String[] args){
String[] itemName = {"Coffee, Water, Milk, Donut, Bagel"};
double[] itemPrice = {1.00, 2.00, 1.50, 0.75, 1.25};
Scanner input = new Scanner(System.in);
String decision;
System.out.println ("Welcome to Wings Coffee Shop");
System.out.println ("We have a great list of tasty items on our menu.");
System.out.println ("Would you like to see these items sorted by");
System.out.println ("name or by price? (n/p): ");
decision = input.nextLine();
if (decision == "n"){
sortName(itemName);
}
else {
sortPrice(itemPrice);
}
}
//method to sort by item name and display
public static void sortName (String[] array){
for (int i = 0; i < array.length; i++){
System.out.println (array[i].toString());
}
}
//method to sort by item price and display
public static void sortPrice (double[] array){
for (int i = 0; i < array.length; i++){
System.out.println (array[i]);
}
}
}
public class Item {
private String name;
private double price;
Item(String itemName, double itemPrice){
itemName = name;
itemPrice= price;
}
public String getName(){
return name;
}
public void setName(String itemName){
itemName = name;
}
public double getPrice(){
return price;
}
public void setPrice(double itemPrice){
itemPrice = price;
}
}
.75
Your program will create a class, named Item. This class has the following:
您的程序将创建一个名为 Item 的类。这个类有以下内容:
- A String instance variable to hold the item name
- A double instance variable to hold the price
- A constructor that takes a String and double to ini
- 用于保存项目名称的 String 实例变量
- 保存价格的双实例变量
- 一个接受 String 和 double 到 ini 的构造函数
Once you have this class created, you write a second class named CoffeeDriver. This class has the following methods:
一旦创建了这个类,就可以编写名为 CoffeeDriver 的第二个类。这个类有以下方法:
- sortName – this method sorts the array of items by item name and then displays the name and price of all items on the screen
- sortPrice – this method sorts the array of items by item price and then displays the name and price of all items on the screen
- main - It creates an array of Item objects using the data above to set each Item's information.
- A get and set method for each instance variable
- sortName – 此方法按商品名称对商品数组进行排序,然后在屏幕上显示所有商品的名称和价格
- sortPrice – 此方法按商品价格对商品数组进行排序,然后在屏幕上显示所有商品的名称和价格
- main - 它使用上面的数据创建一个 Item 对象数组来设置每个 Item 的信息。
- 每个实例变量的 get 和 set 方法
This is all I have so far. I am having a hard time thinking how to sort an array. So if I sort 2 different arrays how do I keep them in proper order. Like for instance coffee = $1
how do I sort it and keep those together.
这就是我迄今为止所拥有的。我很难思考如何对数组进行排序。因此,如果我对 2 个不同的数组进行排序,我该如何保持它们的正确顺序。例如coffee = $1
,我如何对其进行排序并将它们放在一起。
List<Item> items=new ArrayList<Item>();
items.add(new Item("A",1.2));
items.add(new Item("Z",10.2));
items.add(new Item("B",2.3));
items.add(new Item("Y",5.4));
items.add(new Item("B",1.3));
java.util.Collections.sort(items,new Comparator<Item>()
{
public int compare(Item a,Item b)
{
if(a.getName().compareTo(b.getName())>0)
return 1;
else
if(a.getName().compareTo(b.getName())<0)
return -1;
else
return 0;
}
public boolean equals(Object a)
{
return false;
}
});
采纳答案by adatapost
Correction to the Itemclass definition.
对Item类定义的更正。
You need to assign parameters to the fields (In OP you've assign field to parameter)
您需要为字段分配参数(在 OP 中,您已将字段分配给参数)
Use Comparator object parameter to implement sorting for individual field.
使用 Comparator 对象参数实现对单个字段的排序。
class Item {
private final String name;
private final Double cost;
:
: //Getters and setters
:
};
public static void sortByName(List<Item> items) {
Collections.sort(items, new Comparator<Item>() {
public int compare(Object o1, Object o2) {
return (Item)o1.getName().compareTo(o2);
}
public boolean equals(Object o1) {
return ((Item)o1).getName().equals((Item)o2).getName()) )
}
});
public static void sortByPrice(List<Item> items) {
Collections.sort(items, new Comparator<Item>() {
public int compare(Object o1, Object o2) {
return (Item)o1.getCost().compareTo(o2.getCost());
}
public boolean equals(Object o1) {
return ((Item)o1).getCost().equals((Item)o2).getCost()) )
}
});
回答by Kripa
Pseudo Java code (Using an object representation for e.g. (Double) instead of double would be easier as we could make use of the existing compareTo method which is implemented at the object level.)
伪 Java 代码(使用 eg (Double) 而不是 double 的对象表示会更容易,因为我们可以利用在对象级别实现的现有 compareTo 方法。)
##代码##回答by Cameron Skinner
"I am having a hard time thinking how to sort an array"
“我很难思考如何对数组进行排序”
You could take a look at the 'java.util.Collections' class. It contains a bunch of useful methods, including tools for sorting lists. You'll need to read up on how to implement a 'Comparator' object, too.
您可以查看“java.util.Collections”类。它包含许多有用的方法,包括对列表进行排序的工具。您还需要阅读有关如何实现“比较器”对象的信息。
EDIT: Also think carefully about exactly what you want to sort. There is a difference between sorting items by price and sorting the prices.
编辑:还要仔细考虑您想要排序的内容。按价格排序商品和按价格排序是有区别的。
I've assumed this is homework so I won't give you the whole answer, but hopefully this helps.
我假设这是作业,所以我不会给你完整的答案,但希望这会有所帮助。
回答by Tom
Try looking at Arrays.sort that should facilitate what you need.
尝试查看 Arrays.sort 以方便您的需求。
回答by Pa?lo Ebermann
You would not sort both arrays in parallel (which is possible, but not in the Java API, and thus had to be done by yourself), but create Item objects (in a array or collection) from the name and price information, and then sort this array/List (or use a sorted collection like TreeSet).
您不会并行排序两个数组(这是可能的,但不是在 Java API 中,因此必须由您自己完成),而是根据名称和价格信息创建 Item 对象(在数组或集合中),然后对此数组/列表进行排序(或使用像 TreeSet 这样的排序集合)。
For this, you may want to look at java.util.Comparator
and java.util.Collections.sort
(or java.util.Arrays.sort
).
为此,您可能需要查看java.util.Comparator
和java.util.Collections.sort
(或java.util.Arrays.sort
)。