Example usage for java.lang NumberFormatException NumberFormatException

List of usage examples for java.lang NumberFormatException NumberFormatException

Introduction

In this page you can find the example usage for java.lang NumberFormatException NumberFormatException.

Prototype

public NumberFormatException() 

Source Link

Document

Constructs a NumberFormatException with no detail message.

Usage

From source file:Main.java

public static double parseDouble(String s) throws NumberFormatException {
    boolean negative = (s.charAt(0) == '-'); // Check if negative symbol.
    double result = 0.0D; // Starting value
    int index = s.indexOf('.');

    if (index > -1) {
        // Means the decimal place exists, add values to right of it
        int divisor = 1;
        for (int i = index + 1; i < s.length(); i++) {
            divisor *= 10;/*from ww w .j  a  v  a 2s.co  m*/
            int curVal = (s.charAt(i) - 48); // Convert char to int
            if (curVal > 9 | curVal < 0)
                throw new NumberFormatException();
            result += ((double) curVal / divisor);
        }
    } else {
        index = s.length(); // If number string had no decimal
    }

    // Now add number characters to left of decimal
    int multiplier = 1;
    // TODO: Note: Sven removed a test here for no decimal place. Unsure if needed.
    // Check old version of SVN to see old line.
    int finish = negative ? 1 : 0; // Determine finishing position

    for (int i = index - 1; i >= finish; i--) {
        int curVal = (s.charAt(i) - 48); // Convert char to int
        if (curVal > 9 | curVal < 0)
            throw new NumberFormatException();
        result += (curVal * multiplier);
        multiplier *= 10;
    }

    return negative ? -result : result;
}

From source file:Main.java

public static void isValidPort(String port) throws Exception {
    try {/*from  w ww.j ava  2s  . c om*/
        int p = Integer.parseInt(port);
        if (p < 1 || p > 65535) {
            throw new NumberFormatException();
        }
    } catch (NumberFormatException e) {
        throw new Exception("Invalid Port Number! '" + port + "'");
    }
}

From source file:Main.java

public static boolean isValidPort(String port) {
    try {//from www. j  a  v a 2  s. co m
        int p = Integer.parseInt(port);
        if (p < 1 || p > 65535) {
            throw new NumberFormatException();
        }
    } catch (NumberFormatException e) {
        return false;
    }
    return true;
}

From source file:Main.java

public static void isValidIP(String ip) throws Exception {
    try {//from   w w w . j a v a  2 s  .  c  om
        String[] octets = ip.split("\\.");
        for (String s : octets) {
            int i = Integer.parseInt(s);
            if (i > 255 || i < 0) {
                throw new NumberFormatException();
            }
        }
    } catch (NumberFormatException e) {
        throw new Exception("Invalid IP address! '" + ip + "'");
    }
}

From source file:com.lfv.lanzius.Main.java

public static void main(String[] args) {

    /*/*from  w ww.  j av  a 2 s . c  o m*/
     * debug levels:
     * error - Runtime errors or unexpected conditions. Expect these to be immediately visible on a status console. See also Internationalization.
     * warn  - Use of deprecated APIs, poor use of API, 'almost' errors, other runtime situations that are undesirable or unexpected, but not necessarily "wrong". Expect these to be immediately visible on a status console. See also Internationalization.
     * info  - Interesting runtime events (startup/shutdown). Expect these to be immediately visible on a console, so be conservative and keep to a minimum. See also Internationalization.
     * debug - detailed information on the flow through the system. Expect these to be written to logs only.
     */

    Log log = null;
    DOMConfigurator conf = new DOMConfigurator();
    DOMConfigurator.configure("data/properties/loggingproperties.xml");
    System.setProperty("org.apache.commons.logging.Log", "org.apache.commons.logging.impl.Log4JLogger");

    try {
        if (args.length >= 1) {
            // Help
            if (args[0].startsWith("-h")) {
                printUsage();
                return;
            }
            // List devices
            else if (args[0].startsWith("-l")) {
                AudioTest.listDevices();
                return;
            }
            // Test seleted device
            else if (args[0].startsWith("-d")) {
                System.setProperty("org.apache.commons.logging.Log",
                        "org.apache.commons.logging.impl.SimpleLog");
                System.setProperty("org.apache.commons.logging.simplelog.defaultlog", "warn");
                try {
                    String option = "all";
                    if (args.length >= 4)
                        option = args[3];

                    if (option.equals("loop:direct"))
                        AudioTest.testDevicesDirect(Integer.parseInt(args[1]), Integer.parseInt(args[2]));
                    else {
                        if (option.indexOf("debug") != -1)
                            System.setProperty("org.apache.commons.logging.simplelog.defaultlog", "debug");

                        AudioTest.testDevices(Integer.parseInt(args[1]), Integer.parseInt(args[2]), option,
                                (args.length >= 5) ? args[4] : null, (args.length >= 6) ? args[5] : null,
                                (args.length >= 7) ? args[6] : null);
                    }
                } catch (Exception ex) {
                    System.out.println();
                    System.out.println(Config.VERSION);
                    System.out.println();
                    System.out.println("Usage:");
                    System.out.println(
                            "  yada.jar -d output_device input_device <option> <jitter_buffer> <output_buffer> <input_buffer>");
                    System.out.println("  option:");
                    System.out.println("    all(default)");
                    System.out.println("    clip");
                    System.out.println("    loop:jspeex");
                    System.out.println("    loop:null");
                    System.out.println("    loop:direct");
                    System.out.println("    loopdebug:jspeex");
                    System.out.println("    loopdebug:null");
                    System.out.println("  jitter_buffer:");
                    System.out.println("    size of jitter buffer in packets (1-20)");
                    System.out.println("  output_buffer:");
                    System.out.println("    size of output buffer in packets (1.0-4.0)");
                    System.out.println("  input_buffer:");
                    System.out.println("    size of input buffer in packets (1.0-4.0)");
                    System.out.println();
                    if (AudioTest.showStackTrace && !(ex instanceof ArrayIndexOutOfBoundsException))
                        ex.printStackTrace();
                }
                //System.out.println("Exiting...");
                return;
            } else if (args[0].startsWith("-m")) {
                System.setProperty("org.apache.commons.logging.Log",
                        "org.apache.commons.logging.impl.SimpleLog");
                System.setProperty("org.apache.commons.logging.simplelog.defaultlog", "warn");
                try {
                    AudioTest.testMicrophoneLevel(Integer.parseInt(args[1]));
                } catch (Exception ex) {
                    System.out.println();
                    System.out.println(Config.VERSION);
                    System.out.println();
                    System.out.println("Usage:");
                    System.out.println("  yada.jar -m input_device");
                    System.out.println();
                    if (AudioTest.showStackTrace && !(ex instanceof ArrayIndexOutOfBoundsException))
                        ex.printStackTrace();
                }
                return;
            } else if (args[0].startsWith("-s")) {
                Packet.randomSeed = 9182736455L ^ System.currentTimeMillis();
                if (args.length > 2 && args[1].startsWith("-configuration")) {
                    String configFilename = args[2];
                    if (args.length > 4 && args[3].startsWith("-exercise")) {
                        String exerciseFilename = args[4];

                        LanziusServer.start(configFilename, exerciseFilename);
                    } else {
                        LanziusServer.start(configFilename);
                    }
                } else {
                    LanziusServer.start();
                }
                return;
            } else if (args[0].startsWith("-f")) {
                System.setProperty("org.apache.commons.logging.Log",
                        "org.apache.commons.logging.impl.SimpleLog");
                System.setProperty(
                        "org.apache.commons.logging.simplelog.log.com.lfv.lanzius.application.FootSwitchController",
                        "debug");
                try {
                    System.out.println("Starting footswitch controller test using device " + args[1]);
                    try {
                        boolean inverted = false;
                        if (args.length >= 3)
                            inverted = args[2].toLowerCase().startsWith("inv");
                        FootSwitchController c = new FootSwitchController(null, args[1],
                                Constants.PERIOD_FTSW_CONNECTED, inverted);
                        c.start();
                        Thread.sleep(30000);
                    } catch (UnsatisfiedLinkError err) {
                        if (args.length > 1)
                            System.out.println("UnsatisfiedLinkError: " + err.getMessage());
                        else
                            throw new ArrayIndexOutOfBoundsException();
                        System.out.println("Missing ftsw library (ftsw.dll or libftsw.so)");
                        if (!args[1].equalsIgnoreCase("ftdi"))
                            System.out
                                    .println("Missing rxtxSerial library (rxtxSerial.dll or librxtxSerial.so)");
                        if (AudioTest.showStackTrace)
                            err.printStackTrace();
                    }
                } catch (Exception ex) {
                    if (ex instanceof NoSuchPortException)
                        System.out.println("The serial port " + args[1] + " does not exist!");
                    else if (ex instanceof PortInUseException)
                        System.out.println("The serial port " + args[1] + " is already in use!");
                    System.out.println();
                    System.out.println(Config.VERSION);
                    System.out.println();
                    System.out.println("Usage:");
                    System.out.println("  yada.jar -f interface <invert>");
                    System.out.println("  interface:");
                    System.out.println("    ftdi");
                    System.out.println("    comport (COMx or /dev/ttyx)");
                    System.out.println("  invert:");
                    System.out.println("    true");
                    System.out.println("    false (default)");
                    System.out.println();
                    if (AudioTest.showStackTrace && !(ex instanceof ArrayIndexOutOfBoundsException))
                        ex.printStackTrace();
                }
                return;
            } else if (args[0].startsWith("-c")) {
                Packet.randomSeed = 7233103157L ^ System.currentTimeMillis();
                if (args.length >= 2) {
                    try {
                        int id = Integer.valueOf(args[1]);
                        if (id <= 0)
                            throw new NumberFormatException();
                        Controller c = Controller.getInstance();
                        if (args.length >= 3) {
                            if (args[2].equalsIgnoreCase("test")) {
                                c.setAutoTester(true);
                            }
                        }
                        c.init(id);
                        return;
                    } catch (NumberFormatException ex) {
                        printUsage();
                    }
                } else {
                    Controller.getInstance().init(0);
                }
            } else
                printUsage();
        } else
            printUsage();
    } catch (Throwable t) {
        if (log == null)
            log = LogFactory.getLog(Main.class);
        log.error("Unhandled exception or error", t);
    }
}

From source file:Main.java

public static boolean isValidPort(String port) {
    // If the port is left blank/empty we assume the default value was intended
    if (port.equals(null) || port.trim().equals("")) {
        return true;
    }//from  w  w w  .  j  av  a 2  s . c  o  m
    try {
        int p = Integer.parseInt(port);
        if (p < 1 || p > 65535) {
            throw new NumberFormatException();
        }
    } catch (NumberFormatException e) {
        return false;
    }
    return true;
}

From source file:org.codinjutsu.tools.jenkins.view.validator.StrictPositiveIntegerValidator.java

public void validate(JTextField component) throws ConfigurationException {
    String value = component.getText();
    if (component.isEnabled() && StringUtils.isNotEmpty(value)) { //TODO A revoir
        try {/*from  w w w.  ja  v  a2s. c  om*/
            int intValue = Integer.parseInt(value);
            if (intValue <= 0) {
                throw new NumberFormatException();
            }
        } catch (NumberFormatException ex) {
            throw new ConfigurationException(String.format("'%s' is not a positive integer", value));
        }
    }
}

From source file:Main.java

/**
 * Parses the string argument as if it was an int value and returns the
 * result. Throws NumberFormatException if the string does not represent an
 * int quantity. The second argument specifies the radix to use when parsing
 * the value.// w w  w .  j  av a  2  s . c  o  m
 *
 * @param chars a string representation of an int quantity.
 * @param radix the base to use for conversion.
 * @return int the value represented by the argument
 * @throws NumberFormatException if the argument could not be parsed as an int quantity.
 */
public static int parseInt(char[] chars, int offset, int len, int radix) throws NumberFormatException {
    if (chars == null || radix < Character.MIN_RADIX || radix > Character.MAX_RADIX) {
        throw new NumberFormatException();
    }
    int i = 0;
    if (len == 0) {
        throw new NumberFormatException("chars length is 0");
    }
    boolean negative = chars[offset + i] == '-';
    if (negative && ++i == len) {
        throw new NumberFormatException("can't convert to an int");
    }
    if (negative == true) {
        offset++;
        len--;
    }
    return parse(chars, offset, len, radix, negative);
}

From source file:ISO8601DateFormat.java

/**
 * @see java.text.DateFormat#parse(String, ParsePosition)
 *//*from  w  ww  . j av  a 2  s  . c om*/
public Date parse(String text, ParsePosition pos) {

    int i = pos.getIndex();

    try {
        int year = Integer.valueOf(text.substring(i, i + 4)).intValue();
        i += 4;

        if (text.charAt(i) != '-') {
            throw new NumberFormatException();
        }
        i++;

        int month = Integer.valueOf(text.substring(i, i + 2)).intValue() - 1;
        i += 2;

        if (text.charAt(i) != '-') {
            throw new NumberFormatException();
        }
        i++;

        int day = Integer.valueOf(text.substring(i, i + 2)).intValue();
        i += 2;

        calendar.set(year, month, day);
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0); // no parts of a second

        i = parseTZ(i, text);

    } catch (NumberFormatException ex) {
        pos.setErrorIndex(i);
        return null;
    } catch (IndexOutOfBoundsException ex) {
        pos.setErrorIndex(i);
        return null;
    } finally {
        pos.setIndex(i);
    }

    return calendar.getTime();
}

From source file:ISO8601DateTimeFormat.java

/**
 * @see DateFormat#parse(String, ParsePosition)
 *///ww  w.  j a  va 2 s  .c  o m
public Date parse(String text, ParsePosition pos) {

    int i = pos.getIndex();

    try {
        int year = Integer.valueOf(text.substring(i, i + 4)).intValue();
        i += 4;

        if (text.charAt(i) != '-') {
            throw new NumberFormatException();
        }
        i++;

        int month = Integer.valueOf(text.substring(i, i + 2)).intValue() - 1;
        i += 2;

        if (text.charAt(i) != '-') {
            throw new NumberFormatException();
        }
        i++;

        int day = Integer.valueOf(text.substring(i, i + 2)).intValue();
        i += 2;

        if (text.charAt(i) != 'T') {
            throw new NumberFormatException();
        }
        i++;

        int hour = Integer.valueOf(text.substring(i, i + 2)).intValue();
        i += 2;

        if (text.charAt(i) != ':') {
            throw new NumberFormatException();
        }
        i++;

        int mins = Integer.valueOf(text.substring(i, i + 2)).intValue();
        i += 2;

        int secs = 0;
        if (i < text.length() && text.charAt(i) == ':') {
            // handle seconds flexible
            i++;

            secs = Integer.valueOf(text.substring(i, i + 2)).intValue();
            i += 2;
        }

        calendar.set(year, month, day, hour, mins, secs);
        calendar.set(Calendar.MILLISECOND, 0); // no parts of a second

        i = parseTZ(i, text);

    } catch (NumberFormatException ex) {
        pos.setErrorIndex(i);
        return null;
    } catch (IndexOutOfBoundsException ex) {
        pos.setErrorIndex(i);
        return null;
    } finally {
        pos.setIndex(i);
    }

    return calendar.getTime();
}