gpt4 book ai didi

java - 如何获取数组列表中以字母 T 开头的名称字符串并显示教师姓名?

转载 作者:行者123 更新时间:2023-12-02 05:28:18 24 4
gpt4 key购买 nike

如何在数组列表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();
}

类接口(interface)管理方法

@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);
}
}

最佳答案

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'.");
}
}

关于java - 如何获取数组列表中以字母 T 开头的名称字符串并显示教师姓名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56214459/

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