我刚写出来了,就是再截取一次不要逗号[Java] 纯文本查看 复制代码 package com.itheima.test;
import java.util.ArrayList;
/*
* Test类
* 成员方法:
* getUser
* main
*/
public class Test {
public static void main(String[] args) {
ArrayList<User> list = new ArrayList<User>();
User u1 = new User("Rose");
User u2 = new User("Jack");
User u3 = new User("Jerry");
User u4 = new User("Ruby");
char ch = 'J';
list.add(u1);
list.add(u2);
list.add(u3);
list.add(u4);
String s = getUser(list, ch);
if (s.length() < 1) {
System.out.println("没有对应的用户信息");
}else {
System.out.println("查询到的人员:" + s);
}
}
public static String getUser(ArrayList<User> list, char ch) {
StringBuilder sb = new StringBuilder();
//遍历集合
String getUser = null;
char[] chs = {ch};
String str = new String(chs);
for (int i = 0; i < list.size(); i++) {
String s = new String();
s = list.get(i).getName();
if (s.startsWith(str)) {
sb.append(s);
if (i != list.size() - 1) {
sb.append(",");
}
}
}
//去除最后的逗号
if (sb.toString().length() >1) {
getUser = sb.toString().substring(0,sb.toString().length()-1);
}else {
getUser = sb.toString();
}
return getUser;
}
}
|