Last active
June 21, 2017 16:22
-
-
Save apetz/83235a093bfddc63607b44a184fc6cf2 to your computer and use it in GitHub Desktop.
Tony's answer to the SF Offline Programming Challenge "Hello World" problem
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 java.util.regex.Pattern; | |
/** | |
* A (very) simple program that takes one optional command-line argument <name> | |
* and prints "Hello, <name>!" to STDOUT | |
* | |
* If no command line argument is provided, the program prints "Hello, world!" instead | |
* | |
* Can be compiled run using the following: | |
* $ javac HelloWorld.java | |
* $ jar cf HelloWorld.jar HelloWorld.class | |
* $ java HelloWorld "Stellan Skarsgård" | |
* | |
* Notes: the minimalist unicode-friendly name-matching regex is from | |
* https://stackoverflow.com/questions/15805555/java-regex-to-validate-full-name-allow-only-spaces-and-letters | |
*/ | |
public class HelloWorld { | |
public static void main(String[] args) { | |
final String name = args.length > 0 ? args[0] : "world"; | |
// verify command line arguments | |
if (args.length > 1) { | |
throw new IllegalArgumentException("Please provide only one name, enclose multi-word names in quotes"); | |
} | |
// validate the name to make sure there is no unsafe characters, this is probably overkill | |
final Pattern nameValidator = Pattern.compile("^[\\p{L} .'-]+$"); | |
if (!nameValidator.matcher(name).matches()) { | |
throw new IllegalArgumentException("Invalid characters found in provided name"); | |
} | |
System.out.print(String.format("Hello, %s!\n", name)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
General greeting output
Targeted greeting output
java HelloWorld
java HelloWorld "Stellan Skarsgård"
Bonus output
java HelloWorld too many cooks
java HelloWorld "mr. Comma,man"