How to Parse Int from Char in Java

0 min read 179 words

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"));
    }
}
Tags:
Andrew
Andrew

Andrew is a visionary software engineer and DevOps expert with a proven track record of delivering cutting-edge solutions that drive innovation at Ataiva.com. As a leader on numerous high-profile projects, Andrew brings his exceptional technical expertise and collaborative leadership skills to the table, fostering a culture of agility and excellence within the team. With a passion for architecting scalable systems, automating workflows, and empowering teams, Andrew is a sought-after authority in the field of software development and DevOps.

Tags