题目:字符串转换为整数。
思路:将字符串转化为整数首先是遍历字符串中的每一个字符,有三种情况:首字符是正号,首字符是负号,首字符非正负号;然后遍历每一个字符进行num = num * 10 + charArray[i] - '0',在进行这个工作之前首先需要对charArray[i]进行是否为数字字符的判断,循环遍历直到结束,输出结果;
注意事项(思考点):(1)字符串中包含有非数字字符;(2)字符串中包含正负符号;(3)考虑最大的正整数;(4)考虑最小的负整数;(4)溢出。
开始时我的想法只考虑了第一,第二种情况:
/**
* 将字符串转换为整数 1:非数字字符 2:正负号
* @author Peter
*/
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String str = sc.nextLine();
int length = str.length();
int number = 0;
char[] charArray = str.toCharArray();
if (charArray[0] == '-') {
for (int i = 1; i < length; i++) {
if (charArray[i] > '9' || charArray[i] < '0') {
System.out.println("输入的字符串中包含非数字字符");
return;
} else {
number = number * 10 + charArray[i] - '0';
}
}
System.out.println(-number);
} else if (charArray[0] == '+') {
for (int i = 1; i < length; i++) {
if (charArray[i] > '9' || charArray[i] < '0') {
System.out.println("输入的字符串中包含非数字字符");
return;
} else {
number = number * 10 + charArray[i] - '0';
}
}
System.out.println(number);
} else {
for (int i = 0; i < length; i++) {
if (charArray[i] > '9' || charArray[i] < '0') {
System.out.println("输入的字符串中包含非数字字符");
return;
} else {
number = number * 10 + charArray[i] - '0';
}
}
System.out.println(number);
}
}
}
源码(考虑了上面所有情况):
package com.chap01.offer01;
import java.util.Scanner;
/**
* 字符串转整形源码
*/
public class Main1 {
/**
* 将字符串转化为整形
* @param s
* @return
* @throws NumberFormatException
*/
public static int parseInt(String s) throws NumberFormatException {
return parseInt(s, 10);
}
/**
* 将字符串转化为整形,其中radix代表基数,即代表你输入的是几进制的字符串。
* @param s
* @param radix
* @return
* @throws NumberFormatException
*/
public static int parseInt(String s, int radix)
throws NumberFormatException {
/*
* WARNING: This method may be invoked early during VM initialization
* before IntegerCache is initialized. Care must be taken to not use the
* valueOf method.
*/
//判断是否为空
if (s == null) {
throw new NumberFormatException("null");
}
//判断不能小于2进制
if (radix < Character.MIN_RADIX) {
throw new NumberFormatException("radix " + radix
+ " less than Character.MIN_RADIX");
}
//判断不能大于36进制 0-9,a-z一共36进制
if (radix > Character.MAX_RADIX) {
throw new NumberFormatException("radix " + radix
+ " greater than Character.MAX_RADIX");
}
int result = 0;
boolean negative = false;
int i = 0, len = s.length();
int limit = -Integer.MAX_VALUE; //-0x7fffffff即:-2147483647
int multmin;
int digit;
if (len > 0) {
char firstChar = s.charAt(0); //取首字符
if (firstChar < '0') { // Possible leading "+" or "-"
if (firstChar == '-') {
negative = true;
limit = Integer.MIN_VALUE; //0x80000000
} else if (firstChar != '+')
throw NumberFormatException.forInputString(s);
if (len == 1) // Cannot have lone "+" or "-"
throw NumberFormatException.forInputString(s);
i++;
}
multmin = limit / radix; //-214748364
while (i < len) {
// Accumulating negatively avoids surprises near MAX_VALUE
digit = Character.digit(s.charAt(i++), radix); //返回指定基数的数值
if (digit < 0) {
throw NumberFormatException.forInputString(s);
}
if (result < multmin) {
throw NumberFormatException.forInputString(s);
}
result *= radix; //字符abc: a*100 + b*10 + c
if (result < limit + digit) {
throw NumberFormatException.forInputString(s);
}
result -= digit;
}
} else {
throw NumberFormatException.forInputString(s);
}
return negative ? result : -result;
}
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
String str = sc.nextLine();
int num = parseInt(str);
System.out.println(num);
}
}
package com.chap01.offer01;
//异常类
public class NumberFormatException extends IllegalArgumentException {
static final long serialVersionUID = -2848938806368998894L;
/**
* Constructs a <code>NumberFormatException</code> with no detail message.
*/
public NumberFormatException() {
super();
}
/**
* Constructs a <code>NumberFormatException</code> with the specified detail
* message.
*
* @param s
* the detail message.
*/
public NumberFormatException(String s) {
super(s);
}
/**
* Factory method for making a <code>NumberFormatException</code> given the
* specified input which caused the error.
*
* @param s
* the input causing the error
*/
static NumberFormatException forInputString(String s) {
return new NumberFormatException("For input string: \"" + s + "\"");
}
}