英文:
Condition for loops in java
问题
我有2个循环。
第一个:
while (part[i].compareToIgnoreCase(part[i-1]) < 0) {
smaller = myarr[i];
myarr[i] = myarr[i-1];
myarr[i-1] = smaller;
i--;
if (i <= 0) {
break;
}
}
第二个:
while (Integer.parseInt(part[i]) < Integer.parseInt(part[i-1])) {
smaller = myarr[i];
myarr[i] = myarr[i-1];
myarr[i-1] = smaller;
i--;
if (i <= 0) {
break;
}
}
如果您注意到,这两个循环执行相同的任务,只是条件不同。这些条件不能同时传递,只能一次使用一个条件(因为这些循环是方法的一部分,分别传入了两个内容不同的字符串数组)。
我可以将这两个循环合并在一起,并做些什么,以便一次只选择一个条件吗?
英文:
I have 2 loops.
The first:
while(part[i].compareToIgnoreCase(part[i-1])<0) {
smaller = myarr[i];
myarr[i] = myarr[i-1];
myarr[i-1] = smaller;
i--;
if(i<=0) {
break;
}
The second:
while(Integer.parseInt(part[i]) < Integer.parseInt(part[i-1])) {
smaller = myarr[i];
myarr[i] = myarr[i-1];
myarr[i-1] = smaller;
i--;
if(i<=0) {
break;
}
If you notice, both the loops perform the same task. Just the conditions are different. The conditions can not be passed in together i.e.only one can be used at a time.(Because these loops are a part of a method and 2 String arrays with different content are passed in.)
Can I somehow merge both of these together and do something so that only one condition is picked up at a time?
答案1
得分: 0
听起来你是在询问如何将一个Predicate
(确切地说是BiPredicate<String, String>
)作为参数传递。
public void bubbleSort(String[] part, BiPredicate<String, String> predicate) {
while(predicate.test(part[i], part[i-1])) {
// 进行冒泡排序操作
}
}
public void bubbleSort(String[] part) {
if (isText) {
bubbleSort(part, (l, r) -> l.compareToIgnoreCase(r) < 0);
} else {
bubbleSort(part, (l, r) -> Integer.parseInt(l) < Integer.parseInt(r));
}
}
尽管如此,有更好的方法来对数组进行排序!
Arrays.sort(part, String::compareToIgnoreCase); // 按文本排序
Arrays.sort(part, Comparator.comparingInt(Integer::parseInt)); // 按数字排序
英文:
Sounds like you are asking how to take a Predicate
(BiPredicate<String, String>
to be precise) as a parameter.
public void bubbleSort(String[] part, BiPredicate<String, String> predicate) {
while(predicate.test(part[i], part[i-1])) {
// Do bubblesort stuff
}
}
public void bubbleSort(String[] part) {
if (isText) {
bubbleSort(part, (l, r) -> l.compareToIgnoreCase(r) < 0);
} else {
bubbleSort(part, (l, r) -> Integer.parseInt(l) < Integer.parseInt(r));
}
}
That said there are better ways to sort arrays!
Arrays.sort(part, String::compareToIgnoreCase); // Sort by text
Arrays.sort(part, Comparator.comparingInt(Integer::parseInt)); // Sort by number
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论