我想对两个并行数组进行排序,一个是 String ,另一个是 double 数据类型

发布于 2024-11-09 09:16:13 字数 221 浏览 0 评论 0原文

我对编程领域比较陌生,我希望你能帮助我对这些数组进行排序。这个想法是在文本区域上显示菜单项并按名称对项目进行排序。并行数组包含食品,另一个数组包含价格。

String[] items  = {"Gatspy", "Coffee", "Chicken", "Mango Juice"};
double[] prices = {8.99, 23.50, 29.90, 7.50};

I'm relatively new to the programming scene and i would like you to assist me with sorting of these arrays. The idea is to display a menu item on a textArea and sort the items by name. The parralel arrays contain food items and the other one prices.

String[] items  = {"Gatspy", "Coffee", "Chicken", "Mango Juice"};
double[] prices = {8.99, 23.50, 29.90, 7.50};

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

憧憬巴黎街头的黎明 2024-11-16 09:16:13

或者如何将商品名称和价格封装在一个类中,然后拥有该类的单个实例数组并使用 Comparator 对它们进行排序?
例如

public class Item {
private String name;
private double price;
...
//getters and setters for name and price
}

...

Item []items = { new Item("Gatspy", 8.99), .... };

...

class ItemComparator implements Comparator {
 public int compare( Object o1, Object o2 ) {
  Item i1 = (Item)o1;
  Item i2 = (Item)o2;
  return i1.getName().compareTo(i2.getName());
 }
}

...

Arrays.sort( items, new ItemComparator() );

Or how about encapsulating the item name and price in a class, then have a single array of instances of this class and use a Comparator to sort them?
E.g.

public class Item {
private String name;
private double price;
...
//getters and setters for name and price
}

...

Item []items = { new Item("Gatspy", 8.99), .... };

...

class ItemComparator implements Comparator {
 public int compare( Object o1, Object o2 ) {
  Item i1 = (Item)o1;
  Item i2 = (Item)o2;
  return i1.getName().compareTo(i2.getName());
 }
}

...

Arrays.sort( items, new ItemComparator() );
心头的小情儿 2024-11-16 09:16:13

首先不要使用数组,使用 <代码>地图。在您的情况下,请使用 TreeMap,它按其键排序。

Map<String, Double> map = new TreeMap<String, Double>();
map.put("Gatspy", 8.99);
// put the other items

现在迭代条目:

for(Map.Entry<String, Double> entry : map.entrySet()){
    System.out.println("<option value=\"" 
                       + entry.getValue() 
                       + "\">" 
                       + entry.getKey() 
                       + "</option>");
}

参考: Java 教程 > 集合跟踪 > 地图界面

Don't use arrays in the first place, use a Map. In your case, use a TreeMap, it's sorted by its keys.

Map<String, Double> map = new TreeMap<String, Double>();
map.put("Gatspy", 8.99);
// put the other items

Now iterate over the entries:

for(Map.Entry<String, Double> entry : map.entrySet()){
    System.out.println("<option value=\"" 
                       + entry.getValue() 
                       + "\">" 
                       + entry.getKey() 
                       + "</option>");
}

Reference: Java Tutorial > Collections Trail > The Map Interface

一抹微笑 2024-11-16 09:16:13

您应该使用对象:

public class Item {
    private String name;
    private double price; // you shouldn't use doubles for money, but this is unrelated

    public Item(String name, double price) {
        this.name = name;
        this.price = price;
    }

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

    public double getPrice() {
        return this.price;
    }
}

然后您可能有一个 Items 数组(或列表):

private Item[] items = new Item[] {new Item("Gtaspy", 8.99), ...};

并且您可以使用 Arrays.sort() (或 Collections.sort() 如果您使用列表而不是数组)。

有关更多详细信息,请阅读有关集合的 Java 教程

You should use objects:

public class Item {
    private String name;
    private double price; // you shouldn't use doubles for money, but this is unrelated

    public Item(String name, double price) {
        this.name = name;
        this.price = price;
    }

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

    public double getPrice() {
        return this.price;
    }
}

Then you may have an array (or a list) of Items :

private Item[] items = new Item[] {new Item("Gtaspy", 8.99), ...};

and you may sort this array using Arrays.sort() (or Collections.sort() if you use a List instead of an array).

Read the Java tutorial on Collections for more details.

一紙繁鸢 2024-11-16 09:16:13

可能的方法可能与此 math3 库中实现的方法相同:
org.apache.commons.math3.util.MathArrays#sortInPlace

/**
 * Sort an array in place and perform the same reordering of entries on
 * other arrays.  This method works the same as the other
 * {@link #sortInPlace(double[], double[][]) sortInPlace} method, but
 * allows the order of the sort to be provided in the {@code dir}
 * parameter.
 *
 * @param x Array to be sorted and used as a pattern for permutation
 * of the other arrays.
 * @param dir Order direction.
 * @param yList Set of arrays whose permutations of entries will follow
 * those performed on {@code x}.
 * @throws DimensionMismatchException if any {@code y} is not the same
 * size as {@code x}.
 * @throws NullArgumentException if {@code x} or any {@code y} is null
 * @since 3.0
 */
public static void sortInPlace(double[] x,
                               final OrderDirection dir,
                               double[] ... yList)
    throws NullArgumentException, DimensionMismatchException {
    if (x == null) {
        throw new NullArgumentException();
    }

    final int len = x.length;
    final List<Pair<Double, double[]>> list
        = new ArrayList<Pair<Double, double[]>>(len);

    final int yListLen = yList.length;
    for (int i = 0; i < len; i++) {
        final double[] yValues = new double[yListLen];
        for (int j = 0; j < yListLen; j++) {
            double[] y = yList[j];
            if (y == null) {
                throw new NullArgumentException();
            }
            if (y.length != len) {
                throw new DimensionMismatchException(y.length, len);
            }
            yValues[j] = y[i];
        }
        list.add(new Pair<Double, double[]>(x[i], yValues));
    }

    final Comparator<Pair<Double, double[]>> comp
        = new Comparator<Pair<Double, double[]>>() {
        public int compare(Pair<Double, double[]> o1,
                           Pair<Double, double[]> o2) {
            int val;
            switch (dir) {
            case INCREASING:
                val = o1.getKey().compareTo(o2.getKey());
            break;
            case DECREASING:
                val = o2.getKey().compareTo(o1.getKey());
            break;
            default:
                // Should never happen.
                throw new MathInternalError();
            }
            return val;
        }
    };

    Collections.sort(list, comp);

    for (int i = 0; i < len; i++) {
        final Pair<Double, double[]> e = list.get(i);
        x[i] = e.getKey();
        final double[] yValues = e.getValue();
        for (int j = 0; j < yListLen; j++) {
            yList[j][i] = yValues[j];
        }
    }
}

Possible approach could be the same as implemented in this math3 library:
org.apache.commons.math3.util.MathArrays#sortInPlace

/**
 * Sort an array in place and perform the same reordering of entries on
 * other arrays.  This method works the same as the other
 * {@link #sortInPlace(double[], double[][]) sortInPlace} method, but
 * allows the order of the sort to be provided in the {@code dir}
 * parameter.
 *
 * @param x Array to be sorted and used as a pattern for permutation
 * of the other arrays.
 * @param dir Order direction.
 * @param yList Set of arrays whose permutations of entries will follow
 * those performed on {@code x}.
 * @throws DimensionMismatchException if any {@code y} is not the same
 * size as {@code x}.
 * @throws NullArgumentException if {@code x} or any {@code y} is null
 * @since 3.0
 */
public static void sortInPlace(double[] x,
                               final OrderDirection dir,
                               double[] ... yList)
    throws NullArgumentException, DimensionMismatchException {
    if (x == null) {
        throw new NullArgumentException();
    }

    final int len = x.length;
    final List<Pair<Double, double[]>> list
        = new ArrayList<Pair<Double, double[]>>(len);

    final int yListLen = yList.length;
    for (int i = 0; i < len; i++) {
        final double[] yValues = new double[yListLen];
        for (int j = 0; j < yListLen; j++) {
            double[] y = yList[j];
            if (y == null) {
                throw new NullArgumentException();
            }
            if (y.length != len) {
                throw new DimensionMismatchException(y.length, len);
            }
            yValues[j] = y[i];
        }
        list.add(new Pair<Double, double[]>(x[i], yValues));
    }

    final Comparator<Pair<Double, double[]>> comp
        = new Comparator<Pair<Double, double[]>>() {
        public int compare(Pair<Double, double[]> o1,
                           Pair<Double, double[]> o2) {
            int val;
            switch (dir) {
            case INCREASING:
                val = o1.getKey().compareTo(o2.getKey());
            break;
            case DECREASING:
                val = o2.getKey().compareTo(o1.getKey());
            break;
            default:
                // Should never happen.
                throw new MathInternalError();
            }
            return val;
        }
    };

    Collections.sort(list, comp);

    for (int i = 0; i < len; i++) {
        final Pair<Double, double[]> e = list.get(i);
        x[i] = e.getKey();
        final double[] yValues = e.getValue();
        for (int j = 0; j < yListLen; j++) {
            yList[j][i] = yValues[j];
        }
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文