SwitchExample.javaFrom WikiJavabuy this book This article shows the use of the switch conditional in Java, this may be useful when need to quickly indentify numbers, for example in the case of menu items. The article show also how to convert a String containing a number into an
Parsing the command line parametersTo start a program in java the JVM by default searches for the The public static void main(String[] args) { the parameter For example: If we create the
The array
these can be accessed singularly with: args[0] args[1] args[2] The easiest block to check if the command line parameters have been inserted properly: if (args.length != 1) { System.err.println("Usage: SwitchExample [1|2|3|4]"); return; } Converting a String containing a number into an intint option = Integer.parseInt(args[0]); The Java API implements for each of the primitive types a correspondent encapsulation Class, in the
The classes for the numeric types all contain the method Thanks to these Classes you can write: int option = Integer.parseInt(args[0]); switch syntaxthe syntax of the switch statement is as follows. switch (key) { case value: break; default: break; } The remember always to write the The codepackage org.wikijava.basics; public class SwitchExample { /** * @param args */ public static void main(String[] args) { if (args.length != 1) { System.err.println("Usage: SwitchExample [1|2|3|4]"); return; } int option = Integer.parseInt(args[0]); switch (option) { case 1: System.out.println("you typed one"); break; case 2: System.out.println("you typed two"); break; case 3: System.out.println("you typed three"); break; case 4: System.out.println("you typed four"); break; default: System.out.println("you typed something unrecognizable"); break; } } }
|
