我面临着创建一个类似Facebook的计数器的挑战,该计数器将显示有多少人喜欢该帖子。我对Java比较陌生,但是已经做到了。我的问题是-编写以下方法是否有更实用,更简短的方法?
我只是在Main中使用一个简单的静态数组调用了users [],并在其中添加了一些名称。
public static void facebookCounter(String users[])
{
if(users.length == 1)
{
System.out.println(users[0] + " liked this");
}
else if(users.length == 2)
{
System.out.println(users[0] + " " + users[1] + " liked this.");
}
else if(users.length > 2)
{
System.out.println(users[0] + " " + users[1] + " and " + (users.length-2) + " others liked this");
}
}
很抱歉,如果我粘贴的代码格式不正确,我将其粘贴到了intelliJ
感谢任何有想法的人!
答案 0 :(得分:0)
另一种方法可能是使用switch语句,而不是if / else:
public static void facebookCounter(String users[]) {
switch (users.length) {
case 0: break;
case 1:
System.out.println(users[0] + " liked this");
break;
case 2:
System.out.println(users[0] + " " + users[1] + " liked this.");
break;
default:
System.out.println(users[0] + " " + users[1] + " and " + (users.length-2) + " others liked this");
}
}
答案 1 :(得分:-1)
我的建议是流式传输前1个或2个数组项(取决于数组的长度),并使用连接空格char收集到String。然后,添加适当的后缀:
public static void facebookCounter(String users[])
{
String msg = IntStream.range(0, Math.min(2, users.length))
.mapToObj(i -> users[i])
.collect(Collectors.joining(" "));
if (users.length > 2) msg += " and " + (users.length-2) + " others";
msg += " liked this";
System.out.println(msg);
}
编辑:
可以在joining()
方法中指定后缀:
System.out.println(
IntStream.range(0, Math.min(2, users.length))
.mapToObj(i -> users[i])
.collect(Collectors.joining(" ", "",
users.length > 2 ? " and " + (users.length-2) + " others liked this" : " liked this"
)
)
);