英文:
How to avoid duplicate string values in a bubble sort algorithm?
问题
我正在努力解决如何在我的排序算法中避免打印重复的名称。
我忽略空字符串的原因是,我正在实现的系统是一个票务预订系统,它只显示名称列表,而不显示空的时间段。
有人可以帮帮我吗?
String[] name = {"fiona", "vacant", "allen", "fiona", "david", "vacant", "vacant"};
for (int i = 0; i <= (name.length - 1); i++) {
for (int j = i + 1; j < name.length; j++) {
if (name[i].compareTo(name[j]) > 0) {
String temp = name[i];
name[i] = name[j];
name[j] = temp;
}
}
if (!name[i].equals("vacant")) {
System.out.println(name[i] + " ");
}
}
英文:
I'm trying to figure out on how can i avoid printing duplicate names in my sorting algorithm.
The reason i'm ignoring the vacant string is that the system i'm implementing, is a ticket booking system which displays a list of only names instead of the vacant slots.
Can some help me please ?
String[] name={"fiona","vacant","allen","fiona","david","vacant","vacant"};
for (int i = 0; i <= (name.length-1); i++){
for (int j = i+1; j < name.length; j++ ){
if (name[i].compareTo(name[j])>0) {
String temp = name[i];
name[i] = name[j];
name[j] = temp;
}
}
if (!name[i].equals("vacant")) {
System.out.println(name[i] + " ");
}
}
</details>
# 答案1
**得分**: 1
只需检查打印的名称是否与先前的名称相同:
```java
String[] name = {"fiona", "vacant", "allen", "fiona", "david", "vacant", "vacant"};
for (int i = 0; i <= (name.length - 1); i++) {
for (int j = i + 1; j < name.length; j++) {
if (name[i].compareTo(name[j]) > 0) {
String temp = name[i];
name[i] = name[j];
name[j] = temp;
}
}
if (!name[i].equals("vacant") && (i == 0 || !name[i - 1].equals(name[i]))) {
System.out.println(name[i] + " ");
}
}
英文:
Just check if the name you are printing is the same as the previous one:
String[] name={"fiona","vacant","allen","fiona","david","vacant","vacant"};
for (int i = 0; i <= (name.length-1); i++){
for (int j = i+1; j < name.length; j++ ){
if (name[i].compareTo(name[j])>0) {
String temp = name[i];
name[i] = name[j];
name[j] = temp;
}
}
if (!name[i].equals("vacant") && (i == 0 || !name[i-1].equals(name[i]))) {
System.out.println(name[i] + " ");
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论