Merge branch 'master' of https://github.com/eugenp/tutorials into BAEL-12800
This commit is contained in:
@@ -15,3 +15,5 @@
|
||||
- [Calculate Percentage in Java](https://www.baeldung.com/java-calculate-percentage)
|
||||
- [Converting Between Byte Arrays and Hexadecimal Strings in Java](https://www.baeldung.com/java-byte-arrays-hex-strings)
|
||||
- [Convert Latitude and Longitude to a 2D Point in Java](https://www.baeldung.com/java-convert-latitude-longitude)
|
||||
- [Reversing a Binary Tree in Java](https://www.baeldung.com/java-reversing-a-binary-tree)
|
||||
- [Find If Two Numbers Are Relatively Prime in Java](https://www.baeldung.com/java-two-relatively-prime-numbers)
|
||||
|
||||
@@ -4,4 +4,3 @@
|
||||
- [Implementing Simple State Machines with Java Enums](https://www.baeldung.com/java-enum-simple-state-machine)
|
||||
- [Converting Between Roman and Arabic Numerals in Java](http://www.baeldung.com/java-convert-roman-arabic)
|
||||
- [Practical Java Examples of the Big O Notation](http://www.baeldung.com/java-algorithm-complexity)
|
||||
- [An Introduction to the Theory of Big-O Notation](http://www.baeldung.com/big-o-notation)
|
||||
@@ -3,5 +3,5 @@
|
||||
## Relevant articles:
|
||||
|
||||
- [String Matching in Groovy](http://www.baeldung.com/)
|
||||
- [Groovy def Keyword]
|
||||
|
||||
- [Groovy def Keyword](https://www.baeldung.com/groovy-def-keyword)
|
||||
- [Pattern Matching in Strings in Groovy](https://www.baeldung.com/groovy-pattern-matching)
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
Dear <% out << (user) %>,
|
||||
Please read the requested article below.
|
||||
<% out << (articleText) %>
|
||||
From,
|
||||
<% out << (signature) %>
|
||||
@@ -0,0 +1,3 @@
|
||||
Dear $user,
|
||||
Thanks for subscribing our services.
|
||||
${signature}
|
||||
+96
@@ -0,0 +1,96 @@
|
||||
package com.baeldung.templateengine
|
||||
|
||||
import groovy.text.SimpleTemplateEngine
|
||||
import groovy.text.StreamingTemplateEngine
|
||||
import groovy.text.GStringTemplateEngine
|
||||
import groovy.text.XmlTemplateEngine
|
||||
import groovy.text.XmlTemplateEngine
|
||||
import groovy.text.markup.MarkupTemplateEngine
|
||||
import groovy.text.markup.TemplateConfiguration
|
||||
|
||||
class TemplateEnginesUnitTest extends GroovyTestCase {
|
||||
|
||||
def bindMap = [user: "Norman", signature: "Baeldung"]
|
||||
|
||||
void testSimpleTemplateEngine() {
|
||||
def smsTemplate = 'Dear <% print user %>, Thanks for reading our Article. ${signature}'
|
||||
def smsText = new SimpleTemplateEngine().createTemplate(smsTemplate).make(bindMap)
|
||||
|
||||
assert smsText.toString() == "Dear Norman, Thanks for reading our Article. Baeldung"
|
||||
}
|
||||
|
||||
void testStreamingTemplateEngine() {
|
||||
def articleEmailTemplate = new File('src/main/resources/articleEmail.template')
|
||||
bindMap.articleText = """1. Overview
|
||||
This is a tutorial article on Template Engines""" //can be a string larger than 64k
|
||||
|
||||
def articleEmailText = new StreamingTemplateEngine().createTemplate(articleEmailTemplate).make(bindMap)
|
||||
|
||||
assert articleEmailText.toString() == """Dear Norman,
|
||||
Please read the requested article below.
|
||||
1. Overview
|
||||
This is a tutorial article on Template Engines
|
||||
From,
|
||||
Baeldung"""
|
||||
|
||||
}
|
||||
|
||||
void testGStringTemplateEngine() {
|
||||
def emailTemplate = new File('src/main/resources/email.template')
|
||||
def emailText = new GStringTemplateEngine().createTemplate(emailTemplate).make(bindMap)
|
||||
|
||||
assert emailText.toString() == "Dear Norman,\nThanks for subscribing our services.\nBaeldung"
|
||||
}
|
||||
|
||||
void testXmlTemplateEngine() {
|
||||
def emailXmlTemplate = '''<xs xmlns:gsp='groovy-server-pages'>
|
||||
<gsp:scriptlet>def emailContent = "Thanks for subscribing our services."</gsp:scriptlet>
|
||||
<email>
|
||||
<greet>Dear ${user}</greet>
|
||||
<content><gsp:expression>emailContent</gsp:expression></content>
|
||||
<signature>${signature}</signature>
|
||||
</email>
|
||||
</xs>'''
|
||||
def emailXml = new XmlTemplateEngine().createTemplate(emailXmlTemplate).make(bindMap)
|
||||
println emailXml.toString()
|
||||
}
|
||||
|
||||
void testMarkupTemplateEngineHtml() {
|
||||
def emailHtmlTemplate = """html {
|
||||
head {
|
||||
title('Service Subscription Email')
|
||||
}
|
||||
body {
|
||||
p('Dear Norman')
|
||||
p('Thanks for subscribing our services.')
|
||||
p('Baeldung')
|
||||
}
|
||||
}"""
|
||||
|
||||
|
||||
def emailHtml = new MarkupTemplateEngine().createTemplate(emailHtmlTemplate).make()
|
||||
println emailHtml.toString()
|
||||
|
||||
}
|
||||
|
||||
void testMarkupTemplateEngineXml() {
|
||||
def emailXmlTemplate = """xmlDeclaration()
|
||||
xs{
|
||||
email {
|
||||
greet('Dear Norman')
|
||||
content('Thanks for subscribing our services.')
|
||||
signature('Baeldung')
|
||||
}
|
||||
}
|
||||
"""
|
||||
TemplateConfiguration config = new TemplateConfiguration()
|
||||
config.autoIndent = true
|
||||
config.autoEscape = true
|
||||
config.autoNewLine = true
|
||||
|
||||
def emailXml = new MarkupTemplateEngine(config).createTemplate(emailXmlTemplate).make()
|
||||
|
||||
println emailXml.toString()
|
||||
}
|
||||
|
||||
}
|
||||
@@ -2,5 +2,5 @@
|
||||
|
||||
## Relevant articles:
|
||||
|
||||
- [Maps in Groovy](http://www.baeldung.com/)
|
||||
- [Maps in Groovy](https://www.baeldung.com/groovy-maps)
|
||||
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
## Relevant Articles
|
||||
|
||||
- [Extending an Array’s Length](https://www.baeldung.com/java-array-add-element-at-the-end)
|
||||
+52
@@ -0,0 +1,52 @@
|
||||
package com.baeldung.array.conversions;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.function.IntFunction;
|
||||
import java.util.stream.IntStream;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
public class StreamArrayConversion {
|
||||
|
||||
public static String[] stringStreamToStringArrayUsingFunctionalInterface(Stream<String> stringStream) {
|
||||
IntFunction<String[]> intFunction = new IntFunction<String[]>() {
|
||||
@Override
|
||||
public String[] apply(int value) {
|
||||
return new String[value];
|
||||
}
|
||||
};
|
||||
|
||||
return stringStream.toArray(intFunction);
|
||||
}
|
||||
|
||||
public static String[] stringStreamToStringArrayUsingMethodReference(Stream<String> stringStream) {
|
||||
return stringStream.toArray(String[]::new);
|
||||
}
|
||||
|
||||
public static String[] stringStreamToStringArrayUsingLambda(Stream<String> stringStream) {
|
||||
return stringStream.toArray(value -> new String[value]);
|
||||
}
|
||||
|
||||
public static Integer[] integerStreamToIntegerArray(Stream<Integer> integerStream) {
|
||||
return integerStream.toArray(Integer[]::new);
|
||||
}
|
||||
|
||||
public static int[] intStreamToPrimitiveIntArray(Stream<Integer> integerStream) {
|
||||
return integerStream.mapToInt(i -> i).toArray();
|
||||
}
|
||||
|
||||
public static Stream<String> stringArrayToStreamUsingArraysStream(String[] stringArray) {
|
||||
return Arrays.stream(stringArray);
|
||||
}
|
||||
|
||||
public static Stream<String> stringArrayToStreamUsingStreamOf(String[] stringArray) {
|
||||
return Stream.of(stringArray);
|
||||
}
|
||||
|
||||
public static IntStream primitiveIntArrayToStreamUsingArraysStream(int[] intArray) {
|
||||
return Arrays.stream(intArray);
|
||||
}
|
||||
|
||||
public static Stream<int[]> primitiveIntArrayToStreamUsingStreamOf(int[] intArray) {
|
||||
return Stream.of(intArray);
|
||||
}
|
||||
}
|
||||
+70
@@ -0,0 +1,70 @@
|
||||
package com.baeldung.array.conversions;
|
||||
|
||||
import static com.baeldung.array.conversions.StreamArrayConversion.intStreamToPrimitiveIntArray;
|
||||
import static com.baeldung.array.conversions.StreamArrayConversion.integerStreamToIntegerArray;
|
||||
import static com.baeldung.array.conversions.StreamArrayConversion.stringStreamToStringArrayUsingFunctionalInterface;
|
||||
import static com.baeldung.array.conversions.StreamArrayConversion.stringStreamToStringArrayUsingLambda;
|
||||
import static com.baeldung.array.conversions.StreamArrayConversion.stringStreamToStringArrayUsingMethodReference;
|
||||
import static com.baeldung.array.conversions.StreamArrayConversion.stringArrayToStreamUsingArraysStream;
|
||||
import static com.baeldung.array.conversions.StreamArrayConversion.stringArrayToStreamUsingStreamOf;
|
||||
import static com.baeldung.array.conversions.StreamArrayConversion.primitiveIntArrayToStreamUsingArraysStream;
|
||||
import static com.baeldung.array.conversions.StreamArrayConversion.primitiveIntArrayToStreamUsingStreamOf;
|
||||
import static org.junit.Assert.assertArrayEquals;
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import com.google.common.collect.Iterators;
|
||||
import java.util.stream.IntStream;
|
||||
import java.util.stream.Stream;
|
||||
import org.junit.Test;
|
||||
|
||||
public class StreamArrayConversionUnitTest {
|
||||
|
||||
private String[] stringArray = new String[]{"baeldung", "convert", "to", "string", "array"};
|
||||
private Integer[] integerArray = new Integer[]{1, 2, 3, 4, 5, 6, 7};
|
||||
private int[] intPrimitiveArray = new int[]{1, 2, 3, 4, 5, 6, 7};
|
||||
|
||||
@Test
|
||||
public void givenStringStream_thenConvertToStringArrayUsingFunctionalInterface() {
|
||||
Stream<String> stringStream = Stream.of("baeldung", "convert", "to", "string", "array");
|
||||
assertArrayEquals(stringArray, stringStreamToStringArrayUsingFunctionalInterface(stringStream));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenStringStream_thenConvertToStringArrayUsingMethodReference() {
|
||||
Stream<String> stringStream = Stream.of("baeldung", "convert", "to", "string", "array");
|
||||
assertArrayEquals(stringArray, stringStreamToStringArrayUsingMethodReference(stringStream));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenStringStream_thenConvertToStringArrayUsingLambda() {
|
||||
Stream<String> stringStream = Stream.of("baeldung", "convert", "to", "string", "array");
|
||||
assertArrayEquals(stringArray, stringStreamToStringArrayUsingLambda(stringStream));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenIntegerStream_thenConvertToIntegerArray() {
|
||||
Stream<Integer> integerStream = Stream.of(1, 2, 3, 4, 5, 6, 7);
|
||||
assertArrayEquals(integerArray, integerStreamToIntegerArray(integerStream));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenIntStream_thenConvertToIntegerArray() {
|
||||
Stream<Integer> integerStream = IntStream.rangeClosed(1, 7).boxed();
|
||||
assertArrayEquals(intPrimitiveArray, intStreamToPrimitiveIntArray(integerStream));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenStringArray_whenConvertedTwoWays_thenConvertedStreamsAreEqual() {
|
||||
assertTrue(Iterators
|
||||
.elementsEqual(stringArrayToStreamUsingArraysStream(stringArray).iterator(),
|
||||
stringArrayToStreamUsingStreamOf(stringArray).iterator()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenPrimitiveArray_whenConvertedTwoWays_thenConvertedStreamsAreNotEqual() {
|
||||
assertFalse(Iterators.elementsEqual(
|
||||
primitiveIntArrayToStreamUsingArraysStream(intPrimitiveArray).iterator(),
|
||||
primitiveIntArrayToStreamUsingStreamOf(intPrimitiveArray).iterator()));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
### Relevant Articles:
|
||||
- [Java 9 java.lang.Module API](https://www.baeldung.com/java-lambda-effectively-final-local-variables)
|
||||
@@ -7,3 +7,4 @@
|
||||
- [Exploring the New HTTP Client in Java 9 and 11](https://www.baeldung.com/java-9-http-client)
|
||||
- [An Introduction to Epsilon GC: A No-Op Experimental Garbage Collector](https://www.baeldung.com/jvm-epsilon-gc-garbage-collector)
|
||||
- [Guide to jlink](https://www.baeldung.com/jlink)
|
||||
- [Transforming an Empty String into an Empty Optional](https://www.baeldung.com/java-empty-string-to-empty-optional)
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
package com.baeldung.string;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.equalTo;
|
||||
import static org.hamcrest.MatcherAssert.assertThat;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class StringAPITest {
|
||||
|
||||
@Test
|
||||
public void whenPositiveArgument_thenReturnIndentedString() {
|
||||
String multilineStr = "This is\na multiline\nstring.";
|
||||
String outputStr = " This is\n a multiline\n string.\n";
|
||||
|
||||
String postIndent = multilineStr.indent(3);
|
||||
|
||||
assertThat(postIndent, equalTo(outputStr));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenNegativeArgument_thenReturnReducedIndentedString() {
|
||||
String multilineStr = " This is\n a multiline\n string.";
|
||||
String outputStr = " This is\n a multiline\n string.\n";
|
||||
|
||||
String postIndent = multilineStr.indent(-2);
|
||||
|
||||
assertThat(postIndent, equalTo(outputStr));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenTransformUsingLamda_thenReturnTransformedString() {
|
||||
String result = "hello".transform(input -> input + " world!");
|
||||
|
||||
assertThat(result, equalTo("hello world!"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenTransformUsingParseInt_thenReturnInt() {
|
||||
int result = "42".transform(Integer::parseInt);
|
||||
|
||||
assertThat(result, equalTo(42));
|
||||
}
|
||||
}
|
||||
@@ -3,4 +3,5 @@
|
||||
## Core Java 8 Cookbooks and Examples (part 2)
|
||||
|
||||
### Relevant Articles:
|
||||
- [Anonymous Classes in Java](http://www.baeldung.com/)
|
||||
- [Anonymous Classes in Java](https://www.baeldung.com/java-anonymous-classes)
|
||||
- [Run JAR Application With Command Line Arguments](https://www.baeldung.com/java-run-jar-with-arguments)
|
||||
|
||||
+1
-1
@@ -101,7 +101,7 @@ public class OptionalChainingUnitTest {
|
||||
}
|
||||
|
||||
private Optional<String> createOptional(String input) {
|
||||
if (input == null || input == "" || input == "empty") {
|
||||
if (input == null || "".equals(input) || "empty".equals(input)) {
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
|
||||
@@ -20,6 +20,14 @@
|
||||
- [Multi-Release Jar Files](https://www.baeldung.com/java-multi-release-jar)
|
||||
- [Ahead of Time Compilation (AoT)](https://www.baeldung.com/ahead-of-time-compilation)
|
||||
- [Java 9 Process API Improvements](https://www.baeldung.com/java-9-process-api)
|
||||
- [Guide to java.lang.Process API](https://www.baeldung.com/java-process-api)
|
||||
|
||||
|
||||
- [Java 9 java.util.Objects Additions](https://www.baeldung.com/java-9-objects-new)
|
||||
- [Java 9 Reactive Streams](https://www.baeldung.com/java-9-reactive-streams)
|
||||
- [Java 9 Optional API Additions](https://www.baeldung.com/java-9-optional)
|
||||
- [Java 9 CompletableFuture API Improvements](https://www.baeldung.com/java-9-completablefuture)
|
||||
- [Introduction to Java 9 StackWalking API](https://www.baeldung.com/java-9-stackwalking-api)
|
||||
- [Java 9 Convenience Factory Methods for Collections](https://www.baeldung.com/java-9-collections-factory-methods)
|
||||
- [Java 9 Stream API Improvements](https://www.baeldung.com/java-9-stream-api)
|
||||
- [A Guide to Java 9 Modularity](https://www.baeldung.com/java-9-modularity)
|
||||
- [Java 9 Platform Module API](https://www.baeldung.com/java-9-module-api)
|
||||
- [Java 9 Platform Logging API](https://www.baeldung.com/java-9-logging-api)
|
||||
- [Filtering a Stream of Optionals in Java](https://www.baeldung.com/java-filter-stream-of-optional)
|
||||
|
||||
@@ -8,4 +8,5 @@
|
||||
- [A Guide to HashSet in Java](http://www.baeldung.com/java-hashset)
|
||||
- [A Guide to TreeSet in Java](http://www.baeldung.com/java-tree-set)
|
||||
- [Initializing HashSet at the Time of Construction](http://www.baeldung.com/java-initialize-hashset)
|
||||
- [Guide to EnumSet](https://www.baeldung.com/java-enumset)
|
||||
- [Guide to EnumSet](https://www.baeldung.com/java-enumset)
|
||||
- [Set Operations in Java](https://www.baeldung.com/java-set-operations)
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<groupId>com.baeldung.exception.numberformat</groupId>
|
||||
<artifactId>core-java-exceptions</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<name>core-java-exceptions</name>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-java</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<relativePath>../../parent-java</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<version>4.12</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
</project>
|
||||
+154
@@ -0,0 +1,154 @@
|
||||
package com.baeldung.exception.numberformat;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.math.BigInteger;
|
||||
import java.text.NumberFormat;
|
||||
import java.text.ParseException;
|
||||
import java.util.Locale;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
/**
|
||||
* A set of examples tested to show cases where NumberFormatException is thrown and not thrown.
|
||||
*/
|
||||
public class NumberFormatExceptionUnitTest {
|
||||
|
||||
Logger LOG = Logger.getLogger(NumberFormatExceptionUnitTest.class.getName());
|
||||
|
||||
/* ---INTEGER FAIL CASES--- */
|
||||
@Test(expected = NumberFormatException.class)
|
||||
public void givenByteConstructor_whenAlphabetAsInput_thenFail() {
|
||||
Byte byteInt = new Byte("one");
|
||||
}
|
||||
|
||||
@Test(expected = NumberFormatException.class)
|
||||
public void givenShortConstructor_whenSpaceInInput_thenFail() {
|
||||
Short shortInt = new Short("2 ");
|
||||
}
|
||||
|
||||
@Test(expected = NumberFormatException.class)
|
||||
public void givenParseIntMethod_whenSpaceInInput_thenFail() {
|
||||
Integer aIntPrim = Integer.parseInt("6000 ");
|
||||
}
|
||||
|
||||
@Test(expected = NumberFormatException.class)
|
||||
public void givenParseIntMethod_whenUnderscoreInInput_thenFail() {
|
||||
int bIntPrim = Integer.parseInt("6_000");
|
||||
}
|
||||
|
||||
@Test(expected = NumberFormatException.class)
|
||||
public void givenIntegerValueOfMethod_whenCommaInInput_thenFail() {
|
||||
Integer cIntPrim = Integer.valueOf("6,000");
|
||||
}
|
||||
|
||||
@Test(expected = NumberFormatException.class)
|
||||
public void givenBigIntegerConstructor_whenDecimalInInput_thenFail() {
|
||||
BigInteger bigInteger = new BigInteger("4.0");
|
||||
}
|
||||
|
||||
@Test(expected = NumberFormatException.class)
|
||||
public void givenDecodeMethod_whenAlphabetInInput_thenFail() {
|
||||
Long decodeInteger = Long.decode("64403L");
|
||||
}
|
||||
|
||||
/* ---INTEGER PASS CASES--- */
|
||||
@Test
|
||||
public void givenInvalidNumberInputs_whenOptimized_thenPass() {
|
||||
Byte byteInt = new Byte("1");
|
||||
assertEquals(1, byteInt.intValue());
|
||||
|
||||
Short shortInt = new Short("2 ".trim());
|
||||
assertEquals(2, shortInt.intValue());
|
||||
|
||||
Integer aIntObj = Integer.valueOf("6");
|
||||
assertEquals(6, aIntObj.intValue());
|
||||
|
||||
BigInteger bigInteger = new BigInteger("4");
|
||||
assertEquals(4, bigInteger.intValue());
|
||||
|
||||
int aIntPrim = Integer.parseInt("6000 ".trim());
|
||||
assertEquals(6000, aIntPrim);
|
||||
|
||||
int bIntPrim = Integer.parseInt("6_000".replaceAll("_", ""));
|
||||
assertEquals(6000, bIntPrim);
|
||||
|
||||
int cIntPrim = Integer.parseInt("-6000");
|
||||
assertEquals(-6000, cIntPrim);
|
||||
|
||||
Long decodeInteger = Long.decode("644032334");
|
||||
assertEquals(644032334L, decodeInteger.longValue());
|
||||
}
|
||||
|
||||
/* ---DOUBLE FAIL CASES--- */
|
||||
@Test(expected = NumberFormatException.class)
|
||||
public void givenFloatConstructor_whenAlphabetInInput_thenFail() {
|
||||
Float floatDecimalObj = new Float("one.1");
|
||||
}
|
||||
|
||||
@Test(expected = NumberFormatException.class)
|
||||
public void givenDoubleConstructor_whenAlphabetInInput_thenFail() {
|
||||
Double doubleDecimalObj = new Double("two.2");
|
||||
}
|
||||
|
||||
@Test(expected = NumberFormatException.class)
|
||||
public void givenBigDecimalConstructor_whenSpecialCharsInInput_thenFail() {
|
||||
BigDecimal bigDecimalObj = new BigDecimal("3_0.3");
|
||||
}
|
||||
|
||||
@Test(expected = NumberFormatException.class)
|
||||
public void givenParseDoubleMethod_whenCommaInInput_thenFail() {
|
||||
double aDoublePrim = Double.parseDouble("4000,1");
|
||||
}
|
||||
|
||||
/* ---DOUBLE PASS CASES--- */
|
||||
@Test
|
||||
public void givenDoubleConstructor_whenDecimalInInput_thenPass() {
|
||||
Double doubleDecimalObj = new Double("2.2");
|
||||
assertEquals(2.2, doubleDecimalObj.doubleValue(), 0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenDoubleValueOfMethod_whenMinusInInput_thenPass() {
|
||||
Double aDoubleObj = Double.valueOf("-6000");
|
||||
assertEquals(-6000, aDoubleObj.doubleValue(), 0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsDecimalNumber_whenParsedWithNumberFormat_thenPass() throws ParseException {
|
||||
Number parsedNumber = parseNumberWithLocale("4000.1", Locale.US);
|
||||
assertEquals(4000.1, parsedNumber);
|
||||
assertEquals(4000.1, parsedNumber.doubleValue(), 0);
|
||||
assertEquals(4000, parsedNumber.intValue());
|
||||
}
|
||||
|
||||
/**
|
||||
* In most European countries (for example, France), comma is used as decimal in place of period.
|
||||
* @throws ParseException if the input string contains special characters other than comma or decimal.
|
||||
* In this test case, anything after decimal (period) is dropped when a European locale is set.
|
||||
*/
|
||||
@Test
|
||||
public void givenEuDecimalNumberHasComma_whenParsedWithNumberFormat_thenPass() throws ParseException {
|
||||
Number parsedNumber = parseNumberWithLocale("4000,1", Locale.FRANCE);
|
||||
LOG.info("Number parsed is: " + parsedNumber);
|
||||
assertEquals(4000.1, parsedNumber);
|
||||
assertEquals(4000.1, parsedNumber.doubleValue(), 0);
|
||||
assertEquals(4000, parsedNumber.intValue());
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts a string into a number retaining all decimals, and symbols valid in a locale.
|
||||
* @param number the input string for a number.
|
||||
* @param locale the locale to consider while parsing a number.
|
||||
* @return the generic number object which can represent multiple number types.
|
||||
* @throws ParseException when input contains invalid characters.
|
||||
*/
|
||||
private Number parseNumberWithLocale(String number, Locale locale) throws ParseException {
|
||||
locale = locale == null ? Locale.getDefault() : locale;
|
||||
NumberFormat numberFormat = NumberFormat.getInstance(locale);
|
||||
return numberFormat.parse(number);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -40,3 +40,4 @@
|
||||
- [How to Write to a CSV File in Java](https://www.baeldung.com/java-csv)
|
||||
- [List Files in a Directory in Java](https://www.baeldung.com/java-list-directory-files)
|
||||
- [Java InputStream to Byte Array and ByteBuffer](https://www.baeldung.com/convert-input-stream-to-array-of-bytes)
|
||||
- [Introduction to the Java NIO Selector](https://www.baeldung.com/java-nio-selector)
|
||||
|
||||
@@ -4,3 +4,5 @@
|
||||
|
||||
### Relevant Articles:
|
||||
- [Generic Constructors in Java](https://www.baeldung.com/java-generic-constructors)
|
||||
- [Cannot Reference “X” Before Supertype Constructor Has Been Called](https://www.baeldung.com/java-cannot-reference-x-before-supertype-constructor-error)
|
||||
- [Anonymous Classes in Java](https://www.baeldung.com/java-anonymous-classes)
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
## Relevant Articles
|
||||
|
||||
- [Void Type in Java](https://www.baeldung.com/java-void-type)
|
||||
@@ -51,3 +51,4 @@
|
||||
- [Java Bitwise Operators](https://www.baeldung.com/java-bitwise-operators)
|
||||
- [Guide to Creating and Running a Jar File in Java](https://www.baeldung.com/java-create-jar)
|
||||
- [Making a JSON POST Request With HttpURLConnection](https://www.baeldung.com/httpurlconnection-post)
|
||||
- [Convert Hex to ASCII in Java](https://www.baeldung.com/java-convert-hex-to-ascii)
|
||||
|
||||
@@ -454,7 +454,7 @@
|
||||
<gson.version>2.8.2</gson.version>
|
||||
|
||||
<!-- util -->
|
||||
<commons-lang3.version>3.5</commons-lang3.version>
|
||||
<commons-lang3.version>3.9</commons-lang3.version>
|
||||
<commons-io.version>2.5</commons-io.version>
|
||||
<commons-math3.version>3.6.1</commons-math3.version>
|
||||
<decimal4j.version>1.0.3</decimal4j.version>
|
||||
|
||||
+4
-4
@@ -30,7 +30,7 @@ public class RootCauseFinder {
|
||||
private AgeCalculator() {
|
||||
}
|
||||
|
||||
public static int calculateAge(String birthDate) throws CalculationException {
|
||||
public static int calculateAge(String birthDate) {
|
||||
if (birthDate == null || birthDate.isEmpty()) {
|
||||
throw new IllegalArgumentException();
|
||||
}
|
||||
@@ -44,7 +44,7 @@ public class RootCauseFinder {
|
||||
}
|
||||
}
|
||||
|
||||
private static LocalDate parseDate(String birthDateAsString) throws DateParseException {
|
||||
private static LocalDate parseDate(String birthDateAsString) {
|
||||
|
||||
LocalDate birthDate;
|
||||
try {
|
||||
@@ -62,14 +62,14 @@ public class RootCauseFinder {
|
||||
|
||||
}
|
||||
|
||||
static class CalculationException extends Exception {
|
||||
static class CalculationException extends RuntimeException {
|
||||
|
||||
CalculationException(DateParseException ex) {
|
||||
super(ex);
|
||||
}
|
||||
}
|
||||
|
||||
static class DateParseException extends Exception {
|
||||
static class DateParseException extends RuntimeException {
|
||||
|
||||
DateParseException(String input) {
|
||||
super(input);
|
||||
@@ -15,6 +15,7 @@
|
||||
|
||||
<modules>
|
||||
<module>pre-jpms</module>
|
||||
<module>core-java-exceptions</module>
|
||||
</modules>
|
||||
|
||||
</project>
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
## Relevant Articles
|
||||
|
||||
- [Java 9 Migration Issues and Resolutions](https://www.baeldung.com/java-9-migration-issue)
|
||||
File diff suppressed because it is too large
Load Diff
@@ -6,4 +6,5 @@
|
||||
- [Kotlin Scope Functions](https://www.baeldung.com/kotlin-scope-functions)
|
||||
- [Kotlin Annotations](https://www.baeldung.com/kotlin-annotations)
|
||||
- [Split a List into Parts in Kotlin](https://www.baeldung.com/kotlin-split-list-into-parts)
|
||||
- [String Comparison in Kotlin](https://www.baeldung.com/kotlin-string-comparison)
|
||||
- [String Comparison in Kotlin](https://www.baeldung.com/kotlin-string-comparison)
|
||||
- [Guide to JVM Platform Annotations in Kotlin](https://www.baeldung.com/kotlin-jvm-annotations)
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user