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

题目

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

对于正确答案,程序应该返回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,虽然也算正则,哈哈。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容