美文网首页
每日一练81——Java欢迎来到这个城市(8kyu)

每日一练81——Java欢迎来到这个城市(8kyu)

作者: 砾桫_Yvan | 来源:发表于2018-08-25 18:52 被阅读0次

    题目

    创建一个方法sayHello/ say_hello/ SayHello作为输入的名称,城市和州,以欢迎一个人。请注意,这name将是一个由一个或多个值组成的数组,这些值应该连接在一起,每个值之间有一个空格,并且name测试用例中数组的长度会有所不同。

    例:

    sayHello(new String[]{"John", "Smith"}, "Phoenix", "Arizona")

    此示例将返回字符串 Hello, John Smith! Welcome to Phoenix, Arizona!

    import org.junit.Test;
    import static org.junit.Assert.assertEquals;
    
    public class HelloTest {
        
        @Test
        public void test1() throws Exception {
            Hello h = new Hello();
            String[] name = {"John", "Smith"};
            assertEquals("Hello, John Smith! Welcome to Phoenix, Arizona!",
              h.sayHello(name, "Phoenix", "Arizona"));
        }
    }
    

    解题

    My

    public class Hello{
      public String sayHello(String [] name, String city, String state){
        return "Hello, " + String.join(" ",name) + "!" + " Welcome to " + city + ", " + state + "!";
      }
    }
    

    Other

    public class Hello{
      public String sayHello(String[] name, String city, String state){
        return String.format("Hello, %s! Welcome to %s, %s!",String.join(" ", name),city,state);
      }
    }
    

    后记

    1.8的String.join()挺好用的,下次也用String.format()来输出,不让格式很容易出错。

    相关文章

      网友评论

          本文标题:每日一练81——Java欢迎来到这个城市(8kyu)

          本文链接:https://www.haomeiwen.com/subject/jlbgiftx.html