我正在尝试编写一个程序来搜索存储上的并行数组双值一个字符串,我需要能够通过某个值搜索,返回所有值等于或大于数组中的值和相同的索引字符串数组。
我能够像这样编写对数组进行排序的方法
public static void Sortstrength(Double[] strength, String[] names, int sel) //method to sort beers alphabetically up and down
{
String tmpStr; //temp string to help sort array
Double tmpDbl; //temp double to help sort array
if (sel == 1) //sort by names ascending if sel int = 1
{
for (int t = 0; t < strength.length - 1; t++) {
for (int i = 0; i < strength.length - 1; i++) {
if (strength[i].compareTo(strength[i + 1]) > 0) {
tmpStr = names[i];
tmpDbl = strength[i];
names[i] = names[i + 1];
strength[i] = strength[i + 1];
names[i + 1] = tmpStr;
strength[i + 1] = tmpDbl;
}
}
}
for (int i = 0; i < names.length; i++) {
System.out.printf("%-15s %s \n", names[i], strength[i]);
}
} else //sort by names descending
{
for (int t = 0; t < strength.length - 1; t++) {
for (int i = 0; i < strength.length - 1; i++) {
if (strength[i].compareTo(strength[i + 1]) < 0) {
tmpStr = names[i];
tmpDbl = strength[i];
names[i] = names[i + 1];
strength[i] = strength[i + 1];
names[i + 1] = tmpStr;
strength[i + 1] = tmpDbl;
}
}
}
for (int i = 0; i < names.length; i++) {
System.out.printf("%-15s %s \n", names[i], strength[i]);
}
}
}
如果有可能的话,我不知道如何改变这一点,但任何帮助都会受到赞赏,因为我很困难
感谢您的帮助。
答案 0 :(得分:0)
创建一个包含double和字符串值的类Beer。将啤酒添加到列表中并使用Comperator进行排序。输出清单。
public class Beer
{
private final double strength;
private final String name;
public Bear(final String name, final double strength)
{
this.strength = strength;
this.name = name;
}
public String getName() { return name; }
public double getStrength() { return strength; }
}
答案 1 :(得分:0)
要使用按升序排序的strength
数组搜索数据,请使用binarySearch
:
double threshold = 2.0d;
int index = Arrays.binarySearch(strength, threshold);
if (index < 0) {
index = -index - 1;
}
因为你的两个数组是&#34;同步&#34;此索引将与您的String数组匹配。
注意,你可以实现&#34;绑定&#34;强度/名称数据及其排序方式至少以两种不同方式更清晰,更有效:
strength
键是唯一的,然后按键排序。MyData
,如 Hannes 的答案和提供自定义的MyData
Comparator
个{1}}对象数组{{1}},然后使用相同的比较器sort根据您的要求查找索引。答案 2 :(得分:0)
听起来你真正想要的是从双打到弦乐的有序地图。使用TreeMap:
private final TreeMap<Double, String> map = new TreeMap<>(); //for descending order use .reverseMap()
public SortedMap<Double, String> getKeysAbove(double key) {
return map.subMap(key, Double.POSITIVE_INFINITY);
}
public static void exampleUsage() {
Mapper mapper = new Mapper(); //or whatever class name
mapper.map.put(1D, "Goodbye");
mapper.map.put(2D, "Hello, ");
mapper.map.put(3D, "World!");
for (Entry<Double, String> e : mapper.getKeysAbove(1.5).entrySet()) {
System.out.println(e.getKey() + ": " + e.getValue());
}
}