Created
September 22, 2022 12:45
-
-
Save rchatley/848b0679136edcde30e25bb69f6a698a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import org.junit.Test; | |
import java.util.regex.Matcher; | |
import java.util.regex.Pattern; | |
import static org.hamcrest.CoreMatchers.containsString; | |
import static org.hamcrest.CoreMatchers.is; | |
import static org.hamcrest.MatcherAssert.assertThat; | |
import static org.junit.Assert.assertTrue; | |
import static org.junit.Assert.fail; | |
public class JavaTips { | |
@Test | |
public void howToSplitStrings() { | |
String input = "hello-to-everyone"; | |
String[] parts = input.split("-"); | |
assertThat(parts[0], is("hello")); | |
assertThat(parts[1], is("to")); | |
assertThat(parts[2], is("everyone")); | |
} | |
@Test | |
public void usingRegexInJava() { | |
String input = "Today is 22 September"; | |
Pattern regex = Pattern.compile("Today is (\\d+) \\w+"); | |
Matcher matcher = regex.matcher(input); | |
assertTrue(matcher.matches()); | |
assertThat(matcher.group(1), is("22")); | |
} | |
@Test | |
public void convertingStringNumbersToIntegers() { | |
String input = "313"; | |
int number = Integer.parseInt(input); | |
assertThat(number + 1, is(314)); | |
} | |
@Test | |
public void parsingNonNumbersAsIntegersThrowsException() { | |
try { | |
String badInput = "word"; | |
Integer.parseInt(badInput); | |
fail("won't get here"); | |
} catch (NumberFormatException nfe) { | |
assertThat(nfe.getMessage(), containsString("word")); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment