读书人

求解一道java习题:解决方法

发布时间: 2012-02-27 10:00:22 作者: rapoo

求解一道java习题:
求解一道java习题:
将字符串”12”和数字22相加,使用程序求出两数的和

[解决办法]
丢三落四的

Java code
    String src = "12";    int result = Integer.parseInt(src) + 22;    System.out.println(result);
[解决办法]
基础题,发一个全套的。
Java code
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 表示的值

其他类型类似


[解决办法]
在下一向不太爱走寻常路,这里也给个不寻常的解法吧:
Java code
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);


}
}

读书人网 >J2SE开发

热点推荐