int foo;String StringThatCouldBeANumberOrNot = "26263Hello"; //will throw exceptionString StringThatCouldBeANumberOrNot2 = "26263"; //will not throw exceptiontry {foo = Integer.parseInt(StringThatCouldBeANumberOrNot);} catch (NumberFormatException e) {//Will Throw exception!//do something! anything to handle the exception.}
try {foo = Integer.parseInt(StringThatCouldBeANumberOrNot2);} catch (NumberFormatException e) {//No problem this time, but still it is good practice to care about exceptions.//Never trust user input :)//Do something! Anything to handle the exception.}
public static int strToInt(String str){int i = 0;int num = 0;boolean isNeg = false;
// Check for negative sign; if it's there, set the isNeg flagif (str.charAt(0) == '-') {isNeg = true;i = 1;}
// Process each character of the string;while( i < str.length()) {num *= 10;num += str.charAt(i++) - '0'; // Minus the ASCII code of '0' to get the value of the charAt(i++).}
if (isNeg)num = -num;return num;}
// Obtaining the integer values of the char 1 and 2 in ASCIIint semilastdigitASCII = number.charAt(number.length() - 2);int lastdigitASCII = number.charAt(number.length() - 1);
有了代码,我们只需要看看表,并进行必要的调整:
double semilastdigit = semilastdigitASCII - 48; // A quick look, and -48 is the keydouble lastdigit = lastdigitASCII - 48;
try{String stringValue = "1234";
// From String to Integerint integerValue = Integer.valueOf(stringValue);
// Orint integerValue = Integer.ParseInt(stringValue);
// Now from integer to back into stringstringValue = String.valueOf(integerValue);}catch (NumberFormatException ex) {//JOptionPane.showMessageDialog(frame, "Invalid input string!");System.out.println("Invalid input string!");return;}
Option #2: Reset the affected variable if the execution flow can continue in case of an exception. For example, with some modifications in the catch block
// prints "12"System.out.println(tryParseInteger("12").map(i -> i.toString()).orElse("invalid"));// prints "-1"System.out.println(tryParseInteger("-1").map(i -> i.toString()).orElse("invalid"));// prints "invalid"System.out.println(tryParseInteger("ab").map(i -> i.toString()).orElse("invalid"));
public static int parseIntOrDefault(String value, int defaultValue) {int result = defaultValue;try {result = Integer.parseInt(value);}catch (Exception e) {}return result;}
public static int parseIntOrDefault(String value, int beginIndex, int defaultValue) {int result = defaultValue;try {String stringValue = value.substring(beginIndex);result = Integer.parseInt(stringValue);}catch (Exception e) {}return result;}
public static int parseIntOrDefault(String value, int beginIndex, int endIndex, int defaultValue) {int result = defaultValue;try {String stringValue = value.substring(beginIndex, endIndex);result = Integer.parseInt(stringValue);}catch (Exception e) {}return result;}
String a = "10";String a = "10ssda";String a = null;String a = "12102";
if(null != a) {try {int x = Integer.ParseInt(a.trim());Integer y = Integer.valueOf(a.trim());// It will throw a NumberFormatException in case of invalid string like ("10ssda" or "123 212") so, put this code into try catch} catch(NumberFormatException ex) {// ex.getMessage();}}
public class JavaStringToIntExample{public static void main (String[] args){// String s = "test"; // Use this if you want to test the exception belowString s = "1234";
try{// The String to int conversion happens hereint i = Integer.parseInt(s.trim());
// Print out the value after the conversionSystem.out.println("int i = " + i);}catch (NumberFormatException nfe){System.out.println("NumberFormatException: " + nfe.getMessage());}}}
import java.util.*;
public class strToint {
public static void main(String[] args) {
String str = "123";byte barr[] = str.getBytes();
System.out.println(Arrays.toString(barr));int result = 0;
for(int i = 0; i < barr.length; i++) {//System.out.print(barr[i]+" ");int ii = barr[i];char a = (char) ii;int no = Character.getNumericValue(a);result = result * 10 + no;System.out.println(result);}
System.out.println("result:"+result);}}
/** Copyright 2019 Khang Hoang Nguyen* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.* @author: Khang Hoang Nguyen - kevin@fai.host.**/final class faiNumber{private static final long[] longpow = {0L, 1L, 10L, 100L, 1000L, 10000L, 100000L, 1000000L, 10000000L, 100000000L, 1000000000L,10000000000L, 100000000000L, 1000000000000L, 10000000000000L, 100000000000000L,1000000000000000L, 10000000000000000L, 100000000000000000L, 1000000000000000000L,};
private static final int[] intpow = { 0, 1, 10, 100, 1000, 10000,100000, 1000000, 10000000, 100000000, 1000000000};
/*** parseLong(String str) parse a String into Long.* All errors throw by this method is NumberFormatException.* Better errors can be made to tailor to each use case.**/public static long parseLong(final String str) {final int length = str.length();if (length == 0)return 0L;
char c1 = str.charAt(0);int start;
if (c1 == '-' || c1 == '+') {if (length == 1)throw new NumberFormatException(String.format("Not a valid long value. Input '%s'.", str));start = 1;} else {start = 0;}
/** Note: if length > 19, possible scenario is to run through the string* to check whether the string contains only valid digits.* If the check had only valid digits then a negative sign meant underflow, else, overflow.*/if (length - start > 19)throw new NumberFormatException(String.format("Not a valid long value. Input '%s'.", str));
long c;long out = 0L;
for ( ; start < length; start++) {c = (str.charAt(start) ^ '0');if (c > 9L)throw new NumberFormatException( String.format("Not a valid long value. Input '%s'.", str) );out += c * longpow[length - start];}
if (c1 == '-') {out = ~out + 1L;// If out > 0 number underflow(supposed to be negative).if (out > 0L)throw new NumberFormatException(String.format("Not a valid long value. Input '%s'.", str));return out;}// If out < 0 number overflow (supposed to be positive).if (out < 0L)throw new NumberFormatException(String.format("Not a valid long value. Input '%s'.", str));return out;}
/*** parseInt(String str) parse a string into an int.* return 0 if string is empty.**/public static int parseInt(final String str) {final int length = str.length();if (length == 0)return 0;
char c1 = str.charAt(0);int start;
if (c1 == '-' || c1 == '+') {if (length == 1)throw new NumberFormatException(String.format("Not a valid integer value. Input '%s'.", str));start = 1;} else {start = 0;}
int out = 0; int c;int runlen = length - start;
if (runlen > 9) {if (runlen > 10)throw new NumberFormatException(String.format("Not a valid integer value. Input: '%s'.", str));
c = (str.charAt(start) ^ '0'); // <- Any number from 0 - 255 ^ 48 will yield greater than 9 except 48 - 57if (c > 9)throw new NumberFormatException(String.format("Not a valid integer value. Input: '%s'.", str));if (c > 2)throw new NumberFormatException(String.format("Not a valid integer value. Input: '%s'.", str));out += c * intpow[length - start++];}
for ( ; start < length; start++) {c = (str.charAt(start) ^ '0');if (c > 9)throw new NumberFormatException(String.format("Not a valid integer value. Input: '%s'.", str));out += c * intpow[length - start];}
if (c1 == '-') {out = ~out + 1;if (out > 0)throw new NumberFormatException(String.format("Not a valid integer value. Input: '%s'.", str));return out;}
if (out < 0)throw new NumberFormatException(String.format("Not a valid integer value. Input: '%s'.", str));return out;}}
测试代码部分。这应该需要大约200秒左右。
// Int Number Parser Test;long start = System.currentTimeMillis();System.out.println("INT PARSER TEST");for (int i = Integer.MIN_VALUE; i != Integer.MAX_VALUE; i++){if (faiNumber.parseInt(""+i) != i)System.out.println("Wrong");if (i == 0)System.out.println("HalfWay Done");}
if (faiNumber.parseInt("" + Integer.MAX_VALUE) != Integer.MAX_VALUE)System.out.println("Wrong");long end = System.currentTimeMillis();long result = (end - start);System.out.println(result);// INT PARSER END */
另一种方法也非常快。请注意,没有使用int pow数组,而是通过位移位乘以10的数学优化。
public static int parseInt(final String str) {final int length = str.length();if (length == 0)return 0;
char c1 = str.charAt(0);int start;
if (c1 == '-' || c1 == '+') {if (length == 1)throw new NumberFormatException(String.format("Not a valid integer value. Input '%s'.", str));start = 1;} else {start = 0;}
int out = 0;int c;while (start < length && str.charAt(start) == '0')start++; // <-- This to disregard leading 0. It can be// removed if you know exactly your source// does not have leading zeroes.int runlen = length - start;
if (runlen > 9) {if (runlen > 10)throw new NumberFormatException(String.format("Not a valid integer value. Input: '%s'.", str));
c = (str.charAt(start++) ^ '0'); // <- Any number from 0 - 255 ^ 48 will yield greater than 9 except 48 - 57if (c > 9)throw new NumberFormatException(String.format("Not a valid integer value. Input: '%s'.", str));if (c > 2)throw new NumberFormatException(String.format("Not a valid integer value. Input: '%s'.", str));out = (out << 1) + (out << 3) + c; // <- Alternatively this can just be out = c or c above can just be out;}
for ( ; start < length; start++) {c = (str.charAt(start) ^ '0');if (c > 9)throw new NumberFormatException(String.format("Not a valid integer value. Input: '%s'.", str));out = (out << 1) + (out << 3) + c;}
if (c1 == '-') {out = ~out + 1;if (out > 0)throw new NumberFormatException(String.format("Not a valid integer value. Input: '%s'.", str));return out;}
if (out < 0)throw new NumberFormatException(String.format("Not a valid integer value. Input: '%s'.", str));return out;}
public class StringToInteger {public static void main(String[] args) {assert parseInt("123") == Integer.parseInt("123");assert parseInt("-123") == Integer.parseInt("-123");assert parseInt("0123") == Integer.parseInt("0123");assert parseInt("+123") == Integer.parseInt("+123");}
/*** Parse a string to integer** @param s the string* @return the integer value represented by the argument in decimal.* @throws NumberFormatException if the {@code string} does not contain a parsable integer.*/public static int parseInt(String s) {if (s == null) {throw new NumberFormatException("null");}boolean isNegative = s.charAt(0) == '-';boolean isPositive = s.charAt(0) == '+';int number = 0;for (int i = isNegative ? 1 : isPositive ? 1 : 0, length = s.length(); i < length; ++i) {if (!Character.isDigit(s.charAt(i))) {throw new NumberFormatException("s=" + s);}number = number * 10 + s.charAt(i) - '0';}return isNegative ? -number : number;}}
public class NumericStringToInt {
public static void main(String[] args) {String str = "123459";
int num = stringToNumber(str);System.out.println("Number of " + str + " is: " + num);}
private static int stringToNumber(String str) {
int num = 0;int i = 0;while (i < str.length()) {char ch = str.charAt(i);if (ch < 48 || ch > 57)throw new NumberFormatException("" + ch);num = num * 10 + Character.getNumericValue(ch);i++;}return num;}}