检查每个字符的数字 [英] Checking each character for a number
问题描述
我正在尝试循环一个字符串并检查每个字符,如果其中一个字符是数字。如果是数字,我想将其恢复为真。我有一个字符串崩溃,虽然它返回true(它有一个数字)。
I am trying to loop through a string and check each character if one of the characters is a number. If it is a number, I want to return it as true. I have a string "crash", though it returns it as true (that it has a number).
这是我到目前为止所拥有的:
Here's what I have so far:
public boolean isNumber()
{
String newString = "crash";
boolean isNumber = true;
for (int i=0; i<newString.length(); i++)
{
if (Character.isDigit(newString.charAt(i)))
{
isNumber = true;
continue; // continue looping through the string. Go on to the next index.
// The character at index i is a number.
}
else
{
isNumber = false;
break; // terminate the for-loop and return it as false! It is not a number!
}
}
return isNumber;
}
我无法弄清楚出了什么问题。我的逻辑似乎很好,但我的编码不是。
I can't figure out what's wrong. My logic seems to be fine, but my coding isn't.
编辑:我明白了。感谢您的帮助!
I figured it out. Thanks for all your help!
推荐答案
我刚刚运行该代码,我得到 false
,如预期的那样。请仔细检查您是否正确运行。
I just ran that code and I get false
, as expected. Please double-check that you’re running it correctly.
顺便说一下,这是一种表达该功能的简单方法:
Here’s a simpler way to express that function, by the way:
public boolean isNumber(String string) {
for (int i = 0; i < string.length(); i++) {
if (!Character.isDigit(string.charAt(i))) {
return false;
}
}
return true;
}
这篇关于检查每个字符的数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!