gpt4 book ai didi

java - 删除括号 [ ] 和逗号 Java

转载 作者:行者123 更新时间:2023-12-01 08:59:41 28 4
gpt4 key购买 nike

我正在尝试按学生姓氏升序对列表进行排序并显示列表,但我想删除返回 null 的 [, ]。有什么办法让我看不到这一点。

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class StudentTest {

public static void main(String args[]) {
List<Student> list = new ArrayList<Student>();



list.add(new Student(" Gracia", "50","\tCOP2250, COP3250, COP4250"));
list.add(new Student(" Jones", "30", "\tCOP1210, COP3337, COP3530"));
list.add(new Student(" Smith", "10", "\tCOP2250, COP3250, COP4250"));
list.add(new Student(" Wilson", "20", "\tWNC1105, ENC3250, REL2210"));
list.add(new Student(" Braga", "10", "\tENC1105, ENC3250, ISO4250"));
list.add(new Student(" Adams", "20", "\tWNC1105, ENC3250, REL2210"));
list.add(new Student(" Giron", "60","\tCOP1210, COP3337, COP3530"));
list.add(new Student(" O'Neal", "45","\tENC1105, ENC3250, REL2210"));
list.add(new Student(" Ervin", "40", "\tENC1105, COP3250, ISO4250"));
list.add(new Student(" Bourne", "70","\tCOP2250, ENC3250, COP3530"));


System.out.println(list);
Collections.sort(list);
System.out.println(list);

}
}

class Student implements Comparable<Student> {


public Student(String name, String id, String course) {
this.name = name;
this.id = id;
this.course = course;
}

public String getName() {

return name;
}

public void setName(String name) {
this.name = name;
}

public String getId() {
return id;
}

public void setId(String id) {
this.id = id;
}

public String getCourse() {
return course;
}


public Student(String course) {
this.course = course;
}

private String name;
private String id;
private String course;



@Override
public int compareTo(Student student) {

return name.compareTo(student.name);

}


@Override
public String toString() {


System.out.println("" + id + name + course );

return "";

}
}

输出如下:

10 Smith COP2250, COP3250, COP4250

20 Wilson WNC1105, ENC3250, REL2210

10 Braga ENC1105, ENC3250, ISO4250

20 Adams WNC1105, ENC3250, REL2210

60 Giron COP1210, COP3337, COP3530

45 O'Neal ENC1105, ENC3250, REL2210

40 Ervin ENC1105, COP3250, ISO4250

70 Bourne COP2250, ENC3250, COP3530

[, , , , , , , , , ]

为什么我会收到这条线?

[, , , , , , , , , ]

感谢您的帮助!

最佳答案

当您执行 System.out.println(list); 时,您只需使用 ArrayList.toString() 方法的默认实现,该方法返回列表中的值[] 括号以逗号和空格分隔。您有两个选择:

  1. 自行遍历列表并单独打印每个学生(只要它具有 toString() 方法实现。

  2. 或者您可以使用replaceAll()来替换您现在从list.toString()

    获得的字符串

一般情况下,第一个选项更可取,因为对于常见情况 "[""]"", " 可以是列表元素内的有效字符,并且不得替换。但是,对于小情况,当您确定学生姓名、ID 或类(class)中不会有此类字符时,您可以这样做。

关于java - 删除括号 [ ] 和逗号 Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41783669/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com