gpt4 book ai didi

java - CharSequence 到具有多个 +ve 和 -ve 符号的整数

转载 作者:行者123 更新时间:2023-11-29 05:36:08 28 4
gpt4 key购买 nike

我知道要将字符序列转换为整数,我们可以使用此语句

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

如果

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

这个语句是否仍然运行并根据给定的字符串给出答案-25??

最佳答案

由于 ++-+--25 不是有效整数,您最终会遇到 NumberFormatException

参见 docs of parseInt()

Parses the string argument as a signed decimal integer. The characters in the string must all be decimal digits, except that the first character may be an ASCII minus sign '-' ('\u002D') to indicate a negative value or an ASCII plus sign '+' ('\u002B') to indicate a positive value. The resulting integer value is returned, exactly as if the argument and the radix 10 were given as arguments to the parseInt(java.lang.String, int) method.

所以你可以这样做

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

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

否则,采取必要的步骤来面对Exception :)

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

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

return true; //valid integer
}

然后你的代码看起来像

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

关于java - CharSequence 到具有多个 +ve 和 -ve 符号的整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19488067/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com