用JavaSort the Student list by ascending order of student namesThe following is an example illustrating formatting output. You will need it for task 2 and 3. public class Main { public static void main(String[] args) { String string1 = "Hello"; String string2 = "World"; String string3 = "Java"; System.out.println(String.format("%-10s %-10s %-10s", string1, string2, string3)); } } 格式化打印 代码用会打印出名字和和爱好,爱好的第一位对齐
时间: 2024-04-27 19:22:21 浏览: 107
好的,您想让我帮您用Java对学生名单按照姓名升序进行排序,是这样的吗?如果是的话,您可以使用Java内置的排序函数Arrays.sort()和自定义比较器Comparator来实现。以下是示例代码:
```java
import java.util.Arrays;
import java.util.Comparator;
public class Main {
public static void main(String[] args) {
// 假设学生名单保存在一个Student对象数组中
Student[] students = new Student[] {
new Student("Tom", "Swimming"),
new Student("Alice", "Reading"),
new Student("Bob", "Running"),
new Student("David", "Singing")
};
// 按照姓名升序排序
Arrays.sort(students, new Comparator<Student>() {
@Override
public int compare(Student s1, Student s2) {
return s1.getName().compareTo(s2.getName());
}
});
// 输出排序结果
for (Student s : students) {
System.out.println(String.format("%-10s %10s", s.getName(), s.getHobby()));
}
}
}
class Student {
private String name;
private String hobby;
public Student(String name, String hobby) {
this.name = name;
this.hobby = hobby;
}
public String getName() {
return this.name;
}
public String getHobby() {
return this.hobby;
}
}
```
输出结果:
```
Alice Reading
Bob Running
David Singing
Tom Swimming
```
在输出结果中,姓名和爱好都是左对齐的,并且使用了String.format()函数来进行格式化打印。其中,"%-10s"表示左对齐且占用10个字符的字符串,"%10s"表示右对齐且占用10个字符的字符串。
阅读全文