日期:2014-05-20 浏览次数:21067 次
String src = "12";
int result = Integer.parseInt(src) + 22;
System.out.println(result);
------解决方案--------------------
基础题,发一个全套的。
public final class Test {
public static void main(String[] args) {
String a = "12";
int b = Integer.parseInt(a) + 22;
System.out.println(b);
}
}
------解决方案--------------------
boolean.parseBoolean(String s) 将字符串解析为boolean类型
Integer.parseInt(Sting s) 字符串参数作为有符号的十进制整数进行解析
double.parseDouble(String s) 返回一个新的 double 值,该值被初始化为用指定 String 表示的值
其他类型类似
------解决方案--------------------
在下一向不太爱走寻常路,这里也给个不寻常的解法吧:
public class Test2 {
/**
* @param args
*/
public static void main(String[] args) {
try {
System.out.println(stringAdd("12", Integer.toString(22)));
System.out.println(stringAdd("512", Integer.toString(699)));
} catch (NumberFormatException ex) {
System.out.println("字符串格式错误!");
} catch (NullPointerException ex) {
System.out.println("字符串未赋值!");
}
}
static String stringAdd(String num1, String num2) {
StringBuilder sbResult = new StringBuilder();
int c = 0, index1 = num1.length() - 1, index2 = num2.length() - 1;
if (notAnInteger(num1) || notAnInteger(num2))
throw new NumberFormatException();
while (index1 >= 0 || index2 >= 0) {
char c1 = index1 >= 0 ? num1.charAt(index1) : '0';
char c2 = index2 >= 0 ? num2.charAt(index2) : '0';
char ch = (char) (c1 + c2 + c - '0');
if (ch > '9') {
c = 1;
ch -= 10;
} else
c = 0;
sbResult.insert(0, ch);
index1--;
index2--;
}
sbResult.insert(0, c > 0 ? "1" : "");
return (sbResult.toString());
}
static boolean notAnInteger(String num) {
for (int i = 0; i < num.length(); i++)
if (num.charAt(i) < '0' || num.charAt(i) > '9')
return (true);
return (false);
}
}
------解决方案--------------------
public final class Test {
public static void main(String[] args) {
String str = "12";
int result = Integer.parseInt(str) + 22;
System.out.println(result);
}
}