Advertisement
Guest User

Main Function Example

a guest
Sep 7th, 2014
1,673
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.55 KB | None | 0 0
  1.  
  2. public class Main {
  3.  
  4.     /**
  5.      * @param args
  6.      */
  7.     public static void main(String[] args) {
  8.         int count = 0;//Set our counter
  9.         if(args.length < 1){
  10.             //No parameters is this a problem?
  11.         }
  12.         while(count < args.length){//While we have not reached the end of our arguments keep going.
  13.             switch(args[count]){
  14.                 case "-h"://Display help info
  15.                     System.out.println("This is the help message. Proper command syntax:");
  16.                     System.out.println("cmdline -v: Displays version information");
  17.                     System.out.println("cmdline -h: Displays this help message");
  18.                     System.out.println("cmdline -f [file]: Sets file to file provided");
  19.                     count++;
  20.                 break;             
  21.                 case "-v"://Display version information
  22.                     System.out.println("Cmdline parse sample version 1.0.0");
  23.                     count++;
  24.                 break;
  25.                 case "-f"://This is an example to show you how to handle when you have a parameter that takes info
  26.                     String fileName = args[count+1];//We are getting the filename so set it to the string after -f
  27.                     System.out.println("Input file is "+fileName);//Print out info
  28.                     count = count+2;//Increment counter to next item (skipping filename).
  29.                     //Note this provides no bounds checking so if you pass the parameter without file info it may bomb if at the end
  30.                     //You may also surround it in a try/catch for safety.
  31.                 break;
  32.                 default://If none of your cases match then this is an unrecognized parameter and we will exit.
  33.                     System.out.println("Unrecognized parameter "+args[count]+"\nExiting.");
  34.                     System.exit(-1);                   
  35.                 break;
  36.             }
  37.         }
  38.     }
  39.  
  40. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement