How to Parse Int From Char in Java


The challenge

We take in a String where the first place contains a number, write a function that takes in this String and returns an int containing it.

For correct answer program should return int from 0 to 9.

Assume test input string always valid and may look like “1 year old” or “5 years old”, etc.. The first char is number only.

The solution in Java

We take in a String, and get the first character, which is done by using charAt(0). As this is a char type, we can append a -'0' to it and cast it back to an int using (ing):

public class CharProblem {
  public static int howOld(final String herOld) {

    return (int) herOld.charAt(0)-'0';
  
  }
}

Test cases to validate our code

import static org.junit.Assert.*;
import org.junit.Test;

public class CharProblemTest {
    @Test
    public void test() {
      assertEquals(1, CharProblem.howOld("1 year old"));
      assertEquals(2, CharProblem.howOld("2 years old"));
      assertEquals(3, CharProblem.howOld("3 years old"));
      assertEquals(4, CharProblem.howOld("4 years old"));
      assertEquals(5, CharProblem.howOld("5 years old"));
      assertEquals(6, CharProblem.howOld("6 years old"));
      assertEquals(7, CharProblem.howOld("7 years old"));
      assertEquals(8, CharProblem.howOld("8 years old"));
      assertEquals(9, CharProblem.howOld("9 years old"));
    }
}