KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > sapia > console > Option


1 package org.sapia.console;
2
3
4 /**
5  * Models a command-line option.
6  *
7  * @see org.sapia.console.CmdLine
8  * @author Yanick Duchesne
9  * 23-Dec-02
10  */

11 public class Option extends CmdElement {
12   private String JavaDoc _value;
13
14   /**
15    * Creates and option with the given name.
16    *
17    * @param name the option name.
18    */

19   public Option(String JavaDoc name) {
20     super(name);
21   }
22
23   /**
24    * Creates and option with the given name and value.
25    *
26    * @param name the option name.
27    * @param value the option value.
28    */

29   public Option(String JavaDoc name, String JavaDoc value) {
30     super(name);
31     _value = value;
32   }
33
34   /**
35    * Returns this instance's value.
36    *
37    * @return this option's value as a string, or <code>null</code> if
38    * no value was provided.
39    */

40   public String JavaDoc getValue() {
41     return _value;
42   }
43
44   /**
45    * Returns this option's value as an integer.
46    *
47    * @return this option's value as an <code>int</code>.
48    *
49    * @throws InputException if no value exists or if the value does
50    * not evaluate to an integer.
51    */

52   public int asInt() throws InputException {
53     if (_value == null) {
54       throw new InputException("integer expected for option '" + getName() +
55         "'");
56     }
57
58     try {
59       return Integer.parseInt(_value);
60     } catch (NumberFormatException JavaDoc e) {
61       throw new InputException("integer expected for option '" + getName() +
62         "'");
63     }
64   }
65
66   /**
67    * Returns this option's value as a boolean.
68    *
69    * @return this option's value as a <code>boolean</code>.
70    *
71    * @throws InputException if no value exists.
72    */

73   public boolean asBoolean() throws InputException {
74     if (_value == null) {
75       throw new InputException(
76         "true/false, yes/no or on/off expected for option '" + getName() +
77         "'");
78     }
79
80     return _value.equals("true") || _value.equals("yes") ||
81     _value.equals("on");
82   }
83
84   void setValue(String JavaDoc value) {
85     _value = value;
86   }
87
88   public String JavaDoc toString() {
89     if (_value != null) {
90       return "-" + _name + " " + _value;
91     } else {
92       return "-" + _name;
93     }
94   }
95 }
96
Popular Tags