List of usage examples for java.lang NumberFormatException NumberFormatException
public NumberFormatException(String s)
NumberFormatException
with the specified detail message. From source file:org.regenstrief.util.Util.java
/** * Parses an int from a substring of the given String; should yield the same results as * Integer.parseInt(s.substring(startIndex, endIndex), but should be more efficient * //from w w w.j av a 2s . c om * @param s the String * @param startIndex the start index of the substring * @param endIndex the end index of the substring * @return the int **/ public final static int parseInt(final String s, final int startIndex, final int endIndex) { int n = 0, sign = 1; if (startIndex >= endIndex) { throw new StringIndexOutOfBoundsException(endIndex - startIndex); } for (int i = startIndex; i < endIndex; i++) { final char c = s.charAt(i); if (i == startIndex) { if (c == '-') { sign = -1; continue; } else if (c == '+') { // Java 7 introduced support for leading + character continue; } } if ((c < '0') || (c > '9')) { throw new NumberFormatException(s); } n = (n * 10) + (c - '0'); } return sign * n; }
From source file:org.displaytag.util.NumberUtils.java
/** * <p>Turns a string value into a java.lang.Number.</p> * * <p>First, the value is examined for a type qualifier on the end * (<code>'f','F','d','D','l','L'</code>). If it is found, it starts * trying to create successively larger types from the type specified * until one is found that can represent the value.</p> * * <p>If a type specifier is not found, it will check for a decimal point * and then try successively larger types from <code>Integer</code> to * <code>BigInteger</code> and from <code>Float</code> to * <code>BigDecimal</code>.</p> * * <p>If the string starts with <code>0x</code> or <code>-0x</code>, it * will be interpreted as a hexadecimal integer. Values with leading * <code>0</code>'s will not be interpreted as octal.</p> * * <p>Returns <code>null</code> if the string is <code>null</code>.</p> * * <p>This method does not trim the input string, i.e., strings with leading * or trailing spaces will generate NumberFormatExceptions.</p> * * @param str String containing a number, may be null * @return Number created from the string * @throws NumberFormatException if the value cannot be converted *//*from w w w . j av a 2 s .co m*/ public static Number createNumber(String str) throws NumberFormatException { if (str == null) { return null; } if (StringUtils.isBlank(str)) { throw new NumberFormatException("A blank string is not a valid number"); } if (str.startsWith("--")) { // this is protection for poorness in java.lang.BigDecimal. // it accepts this as a legal value, but it does not appear // to be in specification of class. OS X Java parses it to // a wrong value. return null; } if (str.startsWith("0x") || str.startsWith("-0x")) { return createInteger(str); } char lastChar = str.charAt(str.length() - 1); String mant; String dec; String exp; int decPos = str.indexOf('.'); int expPos = str.indexOf('e') + str.indexOf('E') + 1; if (decPos > -1) { if (expPos > -1) { if (expPos < decPos || expPos > str.length()) { throw new NumberFormatException(str + " is not a valid number."); } dec = str.substring(decPos + 1, expPos); } else { dec = str.substring(decPos + 1); } mant = str.substring(0, decPos); } else { if (expPos > -1) { if (expPos > str.length()) { throw new NumberFormatException(str + " is not a valid number."); } mant = str.substring(0, expPos); } else { mant = str; } dec = null; } if (!Character.isDigit(lastChar) && lastChar != '.') { if (expPos > -1 && expPos < str.length() - 1) { exp = str.substring(expPos + 1, str.length() - 1); } else { exp = null; } //Requesting a specific type.. String numeric = str.substring(0, str.length() - 1); boolean allZeros = isAllZeros(mant) && isAllZeros(exp); switch (lastChar) { case 'l': case 'L': if (dec == null && exp == null && (numeric.charAt(0) == '-' && isDigits(numeric.substring(1)) || isDigits(numeric))) { try { return createLong(numeric); } catch (NumberFormatException nfe) { //Too big for a long } return createBigInteger(numeric); } throw new NumberFormatException(str + " is not a valid number."); case 'f': case 'F': try { Float f = NumberUtils.createFloat(numeric); if (!(f.isInfinite() || (f.floatValue() == 0.0F && !allZeros))) { //If it's too big for a float or the float value = 0 and the string //has non-zeros in it, then float does not have the precision we want return f; } } catch (NumberFormatException nfe) { // ignore the bad number } //$FALL-THROUGH$ case 'd': case 'D': try { Double d = NumberUtils.createDouble(numeric); if (!(d.isInfinite() || (d.floatValue() == 0.0D && !allZeros))) { return d; } } catch (NumberFormatException nfe) { // ignore the bad number } try { return createBigDecimal(numeric); } catch (NumberFormatException e) { // ignore the bad number } //$FALL-THROUGH$ default: throw new NumberFormatException(str + " is not a valid number."); } } else { //User doesn't have a preference on the return type, so let's start //small and go from there... if (expPos > -1 && expPos < str.length() - 1) { exp = str.substring(expPos + 1, str.length()); } else { exp = null; } if (dec == null && exp == null) { //Must be an int,long,bigint try { return createInteger(str); } catch (NumberFormatException nfe) { // ignore the bad number } try { return createLong(str); } catch (NumberFormatException nfe) { // ignore the bad number } return createBigInteger(str); } else { //Must be a float,double,BigDec boolean allZeros = isAllZeros(mant) && isAllZeros(exp); try { Float f = createFloat(str); if (!(f.isInfinite() || (f.floatValue() == 0.0F && !allZeros))) { return f; } } catch (NumberFormatException nfe) { // ignore the bad number } try { Double d = createDouble(str); if (!(d.isInfinite() || (d.doubleValue() == 0.0D && !allZeros))) { return d; } } catch (NumberFormatException nfe) { // ignore the bad number } return createBigDecimal(str); } } }
From source file:com.saggezza.jtracker.track.TrackerC.java
private double dParseCatch(String s) { try {/*from www. j a va2 s . co m*/ return Double.parseDouble(s); } catch (NumberFormatException nfe) { throw new NumberFormatException("Item requires fields: 'sku', 'price','quantity'"); } }
From source file:com.saggezza.jtracker.track.TrackerC.java
private int iParseCatch(String s) { try {//from ww w . jav a2 s .c om return Integer.parseInt(s); } catch (NumberFormatException nfe) { throw new NumberFormatException("Item requires fields: 'sku', 'price','quantity'"); } }
From source file:org.nightlabs.base.ui.exceptionhandler.ExceptionHandlerRegistry.java
/** * Processes exceptionHandler extension-point elements. * For each element one instance of exceptionHandler.class is registered * in the {@link ExceptionHandlerRegistry}. * @param element// www .j ava 2s. co m */ @Override public void processElement(IExtension extension, IConfigurationElement element) throws Exception { if (element.getName().toLowerCase().equals("exceptionhandler")) { //$NON-NLS-1$ String targetType = element.getAttribute("targetType"); //$NON-NLS-1$ IExceptionHandler handler = (IExceptionHandler) element.createExecutableExtension("class"); //$NON-NLS-1$ if (!IExceptionHandler.class.isAssignableFrom(handler.getClass())) throw new IllegalArgumentException("Specified class for element exceptionHandler must implement " //$NON-NLS-1$ + IExceptionHandler.class.getName() + ". " + handler.getClass().getName() + " does not."); //$NON-NLS-1$ //$NON-NLS-2$ int priority = -1; // default => will be changed into 500 String priorityString = element.getAttribute("priority"); //$NON-NLS-1$ if (priorityString != null && !"".equals(priorityString)) { //$NON-NLS-1$ try { priority = Integer.parseInt(priorityString); if (priority < 0 || priority > 1000) throw new NumberFormatException("Out of range!"); //$NON-NLS-1$ } catch (NumberFormatException x) { NumberFormatException y = new NumberFormatException("priority=\"" + priorityString //$NON-NLS-1$ + "\" is not a valid integer in the range between 0 and 1000!"); //$NON-NLS-1$ y.initCause(x); throw y; } } addExceptionHandler(targetType, handler, priority); } else { // wrong element according to schema, probably checked earlier throw new IllegalArgumentException( "Element " + element.getName() + " is not supported by extension-point " + EXTENSION_POINT_ID); //$NON-NLS-1$ //$NON-NLS-2$ } }
From source file:SignificantFigures.java
/** * Parse a number from the given string. * A valid number has an optional sign, some digits * with an optional decimal point, and an optional * scientific notation part consisting of an 'E' followed * by an optional sign, followed by some digits. * * @param number String representation of a number. * @throws NumberFormatException if the string is not a valid number. * * @since ostermillerutils 1.00.00/*from w w w . j ava 2 s. co m*/ */ private void parse(String number) throws NumberFormatException { int length = number.length(); digits = new StringBuffer(length); int state = INITIAL; int mantissaStart = -1; boolean foundMantissaDigit = false; // sometimes we don't know if a zero will be // significant or not when it is encountered. // keep track of the number of them so that // the all can be made significant if we find // out that they are. int zeroCount = 0; int leadZeroCount = 0; for (int i = 0; i < length; i++) { char c = number.charAt(i); switch (c) { case '.': { switch (state) { case INITIAL: case LEADZEROS: { state = LEADZEROSDOT; } break; case MIDZEROS: { // we now know that these zeros // are more than just trailing place holders. for (int j = 0; j < zeroCount; j++) { digits.append('0'); } zeroCount = 0; state = DIGITSDOT; } break; case DIGITS: { state = DIGITSDOT; } break; default: { throw new NumberFormatException("Unexpected character '" + c + "' at position " + i); } } } break; case '+': { switch (state) { case INITIAL: { sign = true; state = LEADZEROS; } break; case MANTISSA: { state = MANTISSADIGIT; } break; default: { throw new NumberFormatException("Unexpected character '" + c + "' at position " + i); } } } break; case '-': { switch (state) { case INITIAL: { sign = false; state = LEADZEROS; } break; case MANTISSA: { state = MANTISSADIGIT; } break; default: { throw new NumberFormatException("Unexpected character '" + c + "' at position " + i); } } } break; case '0': { switch (state) { case INITIAL: case LEADZEROS: { // only significant if number // is all zeros. zeroCount++; leadZeroCount++; state = LEADZEROS; } break; case MIDZEROS: case DIGITS: { // only significant if followed // by a decimal point or nonzero digit. mantissa++; zeroCount++; state = MIDZEROS; } break; case LEADZEROSDOT: { // only significant if number // is all zeros. mantissa--; zeroCount++; state = LEADZEROSDOT; } break; case DIGITSDOT: { // non-leading zeros after // a decimal point are always // significant. digits.append(c); } break; case MANTISSA: case MANTISSADIGIT: { foundMantissaDigit = true; state = MANTISSADIGIT; } break; default: { throw new NumberFormatException("Unexpected character '" + c + "' at position " + i); } } } break; case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': { switch (state) { case INITIAL: case LEADZEROS: case DIGITS: { zeroCount = 0; digits.append(c); mantissa++; state = DIGITS; } break; case MIDZEROS: { // we now know that these zeros // are more than just trailing place holders. for (int j = 0; j < zeroCount; j++) { digits.append('0'); } zeroCount = 0; digits.append(c); mantissa++; state = DIGITS; } break; case LEADZEROSDOT: case DIGITSDOT: { zeroCount = 0; digits.append(c); state = DIGITSDOT; } break; case MANTISSA: case MANTISSADIGIT: { state = MANTISSADIGIT; foundMantissaDigit = true; } break; default: { throw new NumberFormatException("Unexpected character '" + c + "' at position " + i); } } } break; case 'E': case 'e': { switch (state) { case INITIAL: case LEADZEROS: case DIGITS: case LEADZEROSDOT: case DIGITSDOT: { // record the starting point of the mantissa // so we can do a substring to get it back later mantissaStart = i + 1; state = MANTISSA; } break; default: { throw new NumberFormatException("Unexpected character '" + c + "' at position " + i); } } } break; default: { throw new NumberFormatException("Unexpected character '" + c + "' at position " + i); } } } if (mantissaStart != -1) { // if we had found an 'E' if (!foundMantissaDigit) { // we didn't actually find a mantissa to go with. throw new NumberFormatException("No digits in mantissa."); } // parse the mantissa. mantissa += Integer.parseInt(number.substring(mantissaStart)); } if (digits.length() == 0) { if (zeroCount > 0) { // if nothing but zeros all zeros are significant. for (int j = 0; j < zeroCount; j++) { digits.append('0'); } mantissa += leadZeroCount; isZero = true; sign = true; } else { // a hack to catch some cases that we could catch // by adding a ton of extra states. Things like: // "e2" "+e2" "+." "." "+" etc. throw new NumberFormatException("No digits in number."); } } }
From source file:org.lmn.fc.frameworks.starbase.plugins.observatory.ui.instruments.impl.starinettester.dao.StarinetTesterDAO.java
/*********************************************************************************************** * sendUdpDatagram().//ww w . ja v a 2 s . c om * * @param commandmessage * * @return ResponseMessageInterface */ public ResponseMessageInterface sendUdpDatagram(final CommandMessageInterface commandmessage) { final String SOURCE = "StarinetTesterDAO.sendUdpDatagram()"; final int PARAMETER_COUNT = 3; final int CHANNEL_COUNT = 1; final int TIMEOUT_MSEC = 10000; final CommandType commandType; UDPClient clientUDP; ResponseMessageInterface responseMessage; LOGGER.debugTimedEvent(LOADER_PROPERTIES.isTimingDebug(), SOURCE); // Get the latest Resources readResources(); // Don't affect the CommandType of the incoming Command commandType = (CommandType) commandmessage.getCommandType().copy(); clientUDP = null; responseMessage = null; // Do not change any DAO data containers! clearEventLogFragment(); try { final List<ParameterType> listParameters; // We expect three Parameters, the Hostname, Port and Payload listParameters = commandType.getParameterList(); if ((listParameters != null) && (listParameters.size() == PARAMETER_COUNT) && (SchemaDataType.STRING.equals(listParameters.get(0).getInputDataType().getDataTypeName())) && (SchemaDataType.DECIMAL_INTEGER .equals(listParameters.get(1).getInputDataType().getDataTypeName())) && (SchemaDataType.STRING.equals(listParameters.get(2).getInputDataType().getDataTypeName()))) { final String strHostname; final String strPortInput; final int intPort; final String strPayload; final InetAddress inetAddress; final byte[] arrayResponse; strHostname = listParameters.get(0).getValue(); strPortInput = listParameters.get(1).getValue(); strPayload = listParameters.get(2).getValue(); intPort = Integer.parseInt(strPortInput); SimpleEventLogUIComponent.logEvent(getEventLogFragment(), EventStatus.INFO, METADATA_TARGET_STARINET + METADATA_ACTION_REQUEST_UDP + METADATA_HOSTNAME + strHostname + TERMINATOR + SPACE + METADATA_PORT + intPort + TERMINATOR + SPACE + METADATA_PAYLOAD + Utilities.byteArrayToSpacedHex(strPayload.getBytes()) + TERMINATOR, SOURCE, getObservatoryClock()); inetAddress = InetAddress.getByName(strHostname); clientUDP = new UDPClient(inetAddress, intPort, intPort, TIMEOUT_MSEC); // If the payload is longer than the maximum reliable length of a UDP Datagram // (8192) bytes then an IOException is thrown clientUDP.connect(); clientUDP.send(strPayload.getBytes()); // This method blocks until a UDP Datagram is received // This Command is being executed on its own SwingWorker, so this doesn't matter... arrayResponse = clientUDP.receive(); if ((arrayResponse != null) && (arrayResponse.length > 0) && (getRawData() != null)) { final Vector vecResponse; // If we get here, it must have succeeded... // Add one channel of data, the Response // There must be one Calendar and ChannelCount samples in the Vector... vecResponse = new Vector(2); vecResponse.add(getObservatoryClock().getCalendarDateNow()); vecResponse.add(Utilities.byteArrayToSpacedHex(arrayResponse)); getRawData().add(vecResponse); setRawDataChannelCount(CHANNEL_COUNT); setTemperatureChannel(false); // Create the ResponseMessage // The ResponseValue is just 'Ok' commandType.getResponse().setValue(ResponseMessageStatus.SUCCESS.getResponseValue()); responseMessage = ResponseMessageHelper.constructSuccessfulResponse(this, commandmessage, commandType); } else { LOGGER.error(SOURCE + " Can't make response"); } } else { throw new NumberFormatException(ResponseMessageStatus.INVALID_PARAMETER.getName()); } } catch (NumberFormatException exception) { // Invalid Parameters SimpleEventLogUIComponent.logEvent(getEventLogFragment(), EventStatus.FATAL, METADATA_TARGET_STARINET + METADATA_ACTION_REQUEST_UDP + METADATA_EXCEPTION + ERROR_PARSE_INPUT + TERMINATOR + SPACE + METADATA_MESSAGE + exception.getMessage() + TERMINATOR, SOURCE, getObservatoryClock()); } catch (IllegalArgumentException exception) { SimpleEventLogUIComponent.logEvent(getEventLogFragment(), EventStatus.FATAL, METADATA_TARGET_STARINET + METADATA_ACTION_REQUEST_UDP + METADATA_EXCEPTION + ERROR_PARSE_INPUT + TERMINATOR + SPACE + METADATA_MESSAGE + exception.getMessage() + TERMINATOR, SOURCE, getObservatoryClock()); } catch (UnknownHostException exception) { SimpleEventLogUIComponent.logEvent(getEventLogFragment(), EventStatus.WARNING, METADATA_TARGET_STARINET + METADATA_ACTION_REQUEST_UDP + METADATA_EXCEPTION + ERROR_UNKNOWN_HOST + TERMINATOR + SPACE + METADATA_MESSAGE + exception.getMessage() + TERMINATOR, SOURCE, getObservatoryClock()); } catch (PortUnreachableException exception) { SimpleEventLogUIComponent.logEvent(getEventLogFragment(), EventStatus.WARNING, METADATA_TARGET_STARINET + METADATA_ACTION_REQUEST_UDP + METADATA_EXCEPTION + ERROR_PORT + TERMINATOR + SPACE + METADATA_MESSAGE + exception.getMessage() + TERMINATOR, SOURCE, getObservatoryClock()); } catch (SecurityException exception) { SimpleEventLogUIComponent.logEvent(getEventLogFragment(), EventStatus.WARNING, METADATA_TARGET_STARINET + METADATA_ACTION_REQUEST_UDP + METADATA_EXCEPTION + ERROR_SECURITY + TERMINATOR + SPACE + METADATA_MESSAGE + exception.getMessage() + TERMINATOR, SOURCE, getObservatoryClock()); } catch (SocketException exception) { SimpleEventLogUIComponent.logEvent(getEventLogFragment(), EventStatus.WARNING, METADATA_TARGET_STARINET + METADATA_ACTION_REQUEST_UDP + METADATA_EXCEPTION + ERROR_SOCKET + TERMINATOR + SPACE + METADATA_MESSAGE + exception.getMessage() + TERMINATOR, SOURCE, getObservatoryClock()); } catch (SocketTimeoutException exception) { SimpleEventLogUIComponent.logEvent(getEventLogFragment(), EventStatus.WARNING, METADATA_TARGET_STARINET + METADATA_ACTION_REQUEST_UDP + METADATA_EXCEPTION + ERROR_TIMEOUT + TERMINATOR + SPACE + METADATA_MESSAGE + exception.getMessage() + TERMINATOR, SOURCE, getObservatoryClock()); } catch (IllegalBlockingModeException exception) { SimpleEventLogUIComponent.logEvent(getEventLogFragment(), EventStatus.WARNING, METADATA_TARGET_STARINET + METADATA_ACTION_REQUEST_UDP + METADATA_EXCEPTION + ERROR_ILLEGAL_MODE + TERMINATOR + SPACE + METADATA_MESSAGE + exception.getMessage() + TERMINATOR, SOURCE, getObservatoryClock()); } catch (IOException exception) { SimpleEventLogUIComponent.logEvent(getEventLogFragment(), EventStatus.WARNING, METADATA_TARGET_STARINET + METADATA_ACTION_REQUEST_UDP + METADATA_EXCEPTION + ERROR_IO + TERMINATOR + SPACE + METADATA_MESSAGE + exception.getMessage() + TERMINATOR, SOURCE, getObservatoryClock()); } finally { // Make sure that the Socket is released if (clientUDP != null) { clientUDP.close(); } } // If the Command failed, do not change any DAO data containers! // Our valuable data must remain available for export later... responseMessage = ResponseMessageHelper.constructFailedResponseIfNull(this, commandmessage, commandType, responseMessage); return (responseMessage); }
From source file:com.glaf.core.util.GetterUtils.java
public static long getLongStrict(String value) { int length = value.length(); if (length <= 0) { throw new NumberFormatException("Unable to parse " + value); }// w w w.ja v a 2 s. c o m int index = 0; long limit = -Long.MAX_VALUE; boolean negative = false; char c = value.charAt(0); if (c < CharPool.NUMBER_0) { if (c == CharPool.MINUS) { limit = Long.MIN_VALUE; negative = true; } else if (c != CharPool.PLUS) { throw new NumberFormatException("Unable to parse " + value); } if (length == 1) { throw new NumberFormatException("Unable to parse " + value); } index++; } long smallLimit = limit / 10; long result = 0; while (index < length) { if (result < smallLimit) { throw new NumberFormatException("Unable to parse " + value); } c = value.charAt(index++); if ((c < CharPool.NUMBER_0) || (c > CharPool.NUMBER_9)) { throw new NumberFormatException("Unable to parse " + value); } int number = c - CharPool.NUMBER_0; result *= 10; if (result < (limit + number)) { throw new NumberFormatException("Unable to parse " + value); } result -= number; } if (negative) { return result; } else { return -result; } }
From source file:org.kuali.rice.krad.service.impl.LookupCriteriaGeneratorImpl.java
/** * @throws NumberFormatException if {@code value} is not a valid * representation of a {@code Number}. *//*from w w w. j a va2 s. c o m*/ protected Number cleanNumeric(String value, Class<?> propertyType) { String cleanedValue = value.replaceAll("[^-0-9.]", ""); // ensure only one "minus" at the beginning, if any if (cleanedValue.lastIndexOf('-') > 0) { if (cleanedValue.charAt(0) == '-') { cleanedValue = "-" + cleanedValue.replaceAll("-", ""); } else { cleanedValue = cleanedValue.replaceAll("-", ""); } } // ensure only one decimal in the string int decimalLoc = cleanedValue.lastIndexOf('.'); if (cleanedValue.indexOf('.') != decimalLoc) { cleanedValue = cleanedValue.substring(0, decimalLoc).replaceAll("\\.", "") + cleanedValue.substring(decimalLoc); } Object rv = KRADUtils.hydrateAttributeValue(propertyType, cleanedValue); if (!(rv instanceof Number)) throw new NumberFormatException("Value: " + cleanedValue + " cannot be converted into number type"); return (Number) rv; }
From source file:com.google.android.gms.internal.zzbti.java
private char zzack() throws IOException { if (this.pos != this.limit || zzqe(1)) { char[] cArr = this.zzcpH; int i = this.pos; this.pos = i + 1; char c = cArr[i]; switch (c) { case ConnectionResult.DEVELOPER_ERROR /*10*/: this.zzcpI++; this.zzcpJ = this.pos; return c; case C0394R.styleable.AppCompatTheme_buttonBarPositiveButtonStyle /*98*/: return '\b'; case Quests.SELECT_ENDING_SOON /*102*/: return '\f'; case C0394R.styleable.AppCompatTheme_ratingBarStyleSmall /*110*/: return '\n'; case C0394R.styleable.AppCompatTheme_listMenuViewStyle /*114*/: return '\r'; case 't': return '\t'; case 'u': if (this.pos + 4 <= this.limit || zzqe(4)) { int i2 = this.pos; int i3 = i2 + 4; int i4 = i2; c = '\u0000'; for (i = i4; i < i3; i++) { char c2 = this.zzcpH[i]; c = (char) (c << 4); if (c2 >= '0' && c2 <= '9') { c = (char) (c + (c2 - 48)); } else if (c2 >= 'a' && c2 <= 'f') { c = (char) (c + ((c2 - 97) + 10)); } else if (c2 < 'A' || c2 > 'F') { String str = "\\u"; String valueOf = String.valueOf(new String(this.zzcpH, this.pos, 4)); throw new NumberFormatException( valueOf.length() != 0 ? str.concat(valueOf) : new String(str)); } else { c = (char) (c + ((c2 - 65) + 10)); }/*from www .jav a 2s. c o m*/ } this.pos += 4; return c; } throw zzjZ("Unterminated escape sequence"); default: return c; } } throw zzjZ("Unterminated escape sequence"); }