用java写一个字符串转换成整数的代码
时间: 2023-06-01 17:03:32 浏览: 52
以下是一个简单的Java程序,将字符串转换为整数:
```java
public static int stringToInt(String str) throws NumberFormatException {
if (str == null || str.length() == 0) {
throw new NumberFormatException("String is null or empty");
}
int result = 0;
boolean isNegative = false;
int i = 0;
if (str.charAt(0) == '-') {
isNegative = true;
i++;
}
while (i < str.length()) {
char digit = str.charAt(i);
if (digit < '0' || digit > '9') {
throw new NumberFormatException("String contains non-digit characters");
}
result *= 10;
result += digit - '0';
i++;
}
return isNegative ? -result : result;
}
```
这个方法首先检查字符串是否为空或长度为零,如果是,它会抛出一个 `NumberFormatException` 异常。接着,它检查字符串是否为负数,如果是,就将 `isNegative` 标记设置为 `true` 并将 `i` 增加 1。然后,它遍历字符串中的每个字符,如果字符不是数字,则抛出异常。如果字符是数字,则将结果乘以 10,加上该数字的值,并将 `i` 增加 1。最后,如果字符串是负数,则将结果取反并返回,否则返回正数。