【Java习题程序】带符号“-”字符串转整型

题目:字符串转整型:例如给一个数字字符串。“123”转成数字123  "-123"转成数字-123  “--123”转成数字123

最后有完整代码

思路:

            1、将字符串转化为 字符串数组用split(); 

                           split()方法说明:    https://mp.csdn.net/postedit/89108906

            2、计算出“-”的个数

            3、去除掉“-”   并且使用System.arraycopy()   复制到数组

            4、将新数组 转化成字符串,再转成整数类型

            5、加上前面的符号判断。

 

 

源代码:

public class Test {
    public static void change(String word){
        int singel = 0;
        String[] num = word.split("");
        for(String m:num){
            if(m.equals("-")){
                singel++;
            }else if(!m.equals("-")){
                break;
            }
        }
        String[] tmp = new String[num.length-singel];
        System.arraycopy(num,singel,tmp,0,num.length-singel);
        StringBuffer tmp1 = new StringBuffer();
        for(int i = 0; i < tmp.length; i++){
            tmp1.append(tmp[i]);
        }
        String s = tmp1.toString();
        int end1 = Integer.parseInt(s);
        int end = end1*(int)(Math.pow(-1,singel));
        System.out.println(end);
    }

    public static void main(String[] args) { 
        change("----123");
    }
}

 

 

运行结果:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值