美文网首页
每日一练77——Java从char问题解析出int(8kyu)

每日一练77——Java从char问题解析出int(8kyu)

作者: 砾桫_Yvan | 来源:发表于2018-08-20 10:51 被阅读0次

    题目

    问一个小女孩 - “你多大了?”。她总是说奇怪的事情......让我们帮助她!

    对于正确答案,程序应该返回int(从0到9)。

    假设测试输入字符串始终有效,但可能像“1 years old”或“5 years old”等。其中第一个字符只能是数字。

    测试用例:

    import static org.junit.Assert.*;
    import org.junit.Test;
    
    public class CharProblemTest {
        @Test
        public void test1() {
          assertEquals(5, CharProblem.howOld("5 years old"));
          }
        @Test
        public void test2() {  
          assertEquals(9, CharProblem.howOld("9 years old"));
          }
       @Test
       public void test3() {
          assertEquals(1, CharProblem.howOld("1 year old"));
          }
    }
    

    解题

    My

    public class CharProblem {
      public static int howOld(final String herOld) {
        return Integer.parseInt(herOld.split(" ")[0]);
      }
    }
    

    Other

    public class CharProblem {
      public static int howOld(final String herOld) {
      
      return Character.getNumericValue(herOld.charAt(0));
      }
    }
    

    如果是2位的数,这答案似乎就不行了。

    后记

    我想了很久的正经的正则表达式,最后还是灵光乍现,用了split,虽然也算正则,哈哈。

    相关文章

      网友评论

          本文标题:每日一练77——Java从char问题解析出int(8kyu)

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