本文介绍了CharSequence的为Integer多+ ve和-ve signss的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经了解到,转换的CharSequence为整数,我们可以使用下面的语句

i have learned that to convert charsequence to integer we can use this statement

String cs="123";    
int number = Integer.parseInt(cs.toString());

如果

cs = "++-+--25";

将这一声明仍然可以运行,给的答案-25根据给定的字符串??

will this statement still run and give answer -25 according to string given??

推荐答案

您是结了一个 NumberFormatException异常,因为 ++ - + - 25 不是有效的整数。

You are end up with a NumberFormatException since ++-+--25 is not a valid integer.

查看 parseInt函数的文档()

将字符串参数作为有符号的十进制整数。 字符串中的字符必须都是十进制数字,除非第一个字符是ASCII字符的减号' - '('\\ u002D')为指示负值或ASCII加号'+'('\\ u002B')来表示正值。将得到的整数值返回,就好像该参数和基数10作为参数传递给parseInt函数(java.lang.String中,int)方法。

所以,你可以做

CharSequence cs = "-25"; //gives you -25

CharSequence cs = "+25";   //gives you 25

否则,采取必要的措施来面对例外:)

所以知道字符序列是一个有效的字符串只写一个简单的方法来返回true或false,然后再继续。

So know the char Sequence is a valid string just write a simple method to return true or false and then proceed further

public static boolean  {
    try { 
        Integer.parseInt(s); 
    } catch(NumberFormatException e) { 
        return false;  // no boss you entered a wrong format
    }

    return true; //valid integer
}

那么你的code看起来像

Then your code looks like

if(isInteger(cs.toString())){
int number = Integer.parseInt(cs.toString());
// proceed remaining
}else{
// No, Operation cannot be completed.Give proper input.
}

这篇关于CharSequence的为Integer多+ ve和-ve signss的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 13:50