CodeWars 여덞 번째 문제

Updated:

Who likes it?

class Solution {
    public static String whoLikesIt(String... names) {
      int length = names.length;
      String text = null;
      
      if(length == 0) {
        text = "no one likes this";
      } else if(length == 1) {
        text = names[0] + " likes this";
      } else if(length == 2) {
        text = names[0] + " and " + names[1] + " like this";
      } else if(length == 3){
        text = names[0] + ", " + names[1] +" and " + names[2] + " like this";
      } else {
        text = names[0] + ", " + names[1] +" and " + (length-2) + " others like this";
      }
      
        return text;
    }
}

*어렵지 않은 문제였지만 여기서 가변인자에 대해서 한 번 짚고 넘어가면 좋을듯.

*가변인자는 메소드가 받는 매개변수의 개수가 사용자에 쓰임에 따라 달라질때 사용

*가변인자는 내부적으로 배열을 생성하여 사용

*가변인자는 오버로딩 사용시 부적합.

ex)

void sum(String s, String...str) {
    for(String a:str)
    System.out.print(a+s);
}
void sum(String...str) {
    for(String a:str)
    System.out.print(a);
}
public static void main(String args[]) {
    Varargs v = new Varargs();
    v.sum("-","a","b","c"); // 위에 것인지 아래 것인지 오류
}

*오버로딩의 조건

  1. 메소드의 이름이 같아야함
  2. 매개변수의 개수 or 타입이 달라야함