Skip to content

Instantly share code, notes, and snippets.

@soren
Created November 15, 2012 07:51
Show Gist options
  • Select an option

  • Save soren/4077280 to your computer and use it in GitHub Desktop.

Select an option

Save soren/4077280 to your computer and use it in GitHub Desktop.
import java.util.HashMap;
import java.util.Map;
import com.google.common.collect.ImmutableMap;
public class PrintOS {
private static final Map<String, String> MSG = ImmutableMap
.of("unix", "This is a UNIX box and therefore good.",
"windows", "This is a Windows box and therefore bad.",
"mac", "This is a Macintosh box and therefore far superior.");
private static final Map<String, String> OS_TYPES = ImmutableMap.<String, String> builder()
.put("SunOS", MSG.get("unix"))
.put("Linux", MSG.get("unix"))
.put("Windows 7", MSG.get("windows"))
.put("Windows NT", MSG.get("windows"))
.put("Windows 95", MSG.get("windows"))
.put("Mac OS", MSG.get("mac"))
.build();
public static void main(final String[] args) {
String osName = System.getProperty("os.name") ;
System.out.println(OS_TYPES.containsKey(osName) ?
OS_TYPES.get(osName) :
"This is not a box. It's a \"" + osName + "\"");
}
}
@soren
Copy link
Copy Markdown
Author

soren commented Nov 15, 2012

Now it works on Windows 7, it also tells you what it thinks the "box" is, if it is unknown.

@soren
Copy link
Copy Markdown
Author

soren commented Nov 15, 2012

Refactored into using to static Maps. The main logic is now a simple if-else construct.

@soren
Copy link
Copy Markdown
Author

soren commented Nov 15, 2012

The if-else construct was very verbose, as we just wanted to print one of two messages, thus it can be replaces by a ternary conditional expression.

@soren
Copy link
Copy Markdown
Author

soren commented Nov 15, 2012

Reformatted to K&R style.

@soren
Copy link
Copy Markdown
Author

soren commented Nov 15, 2012

Added Mac OS - that was easy.

@soren
Copy link
Copy Markdown
Author

soren commented Nov 15, 2012

Using Google's Guava library makes the initialization of the Maps simpler and better. Compile and run using:

$ javac -cp guava-13.0.jar PrintOS.java
$ java -cp guava-13.0.jar:. PrintOS

Get gauva-13.jar from https://code.google.com/p/guava-libraries/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment