在数组列表java中,如何获取以字母“ T”开头的教师姓名列表。我想显示教师的名单名称。如果没有退出教师列表,则会显示“没有老师的名字以字母T开头”。该程序是关于抽象和多态的。这是我的代码
class teacher
package Tinhdahinh;
public abstract class Teacher {
//Properties
int code;
String name;
//method
public Teacher() {
}
public Teacher(int code, String name) {
this.code = code;
this.name = name;
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
// ham hien thi thong tin
void show(){
System.out.print(this.getCode() + "\t" + this.getName());
}
//Ham abstract tinh luong
abstract double getSalary();
}
类接口管理方法
@Override
public void countNameStarByt(ArrayList<Teacher> lst) {
int count = 0;
for (Teacher teacher : lst) {
if(teacher.getName().startsWith("T")){
count++;
// teacher.show();
}
if(count > 0){
System.out.println(count);
teacher.show();
}
else{
System.out.println("No teacher has name starting with letter
'T'.");
break;
}
}
//System.out.println("");
}
public class Main {
public static void main(String[] args) {
Quanly Q = new Quanly();
ArrayList<Teacher> lst = new ArrayList();
Q.inputList(lst, 3);
System.out.println();
System.out.println("Is there any teachers has name starting with letter
'T': ");
Q.countNameStarByt(lst);
}
}
答案 0 :(得分:0)
使用count
是错误的。如果count大于零,则代码将打印出每个Teacher
对象,无论其名称是否以T
开头。如果count
为零,即使列表中有有效的对象,循环也会终止。
尝试:
@Override
public void countNameStarByt(ArrayList<Teacher> lst) {
int count = 0;
for (Teacher teacher: lst) {
if(teacher.getName().startsWith("T")){
count++;
teacher.show();
}
}
if (count == 0) {
System.out.println("No teacher has name starting with letter 'T'.");
}
}
答案 1 :(得分:0)
我可以在您的代码中看到的问题是您编写了break语句的其他部分。因此,在第一次迭代中,如果未找到列表,则控件将位于else中并中断循环。
这可以为您工作
for (Teacher teacher : lst) {
if(teacher.getName().startsWith("T")){
count++;
System.out.println(count);
teacher.show();
}
}
if(count==0){
System.out.println("Teacher not found");
}
答案 2 :(得分:0)
while (Teacher teacher: lst) {
if(teacher.getName().startsWith("T")){
count++;
System.out.println(count);
teacher.show();
}
}
if(count==0){
System.out.println("Teacher not found");
}