[英]What am I doing wrong in this loop?
因此,我正在尝试创建一个布尔方法来检查输入的字符串是否为正整数。 如果它是一个正整数,它将返回 true,如果它是其他任何东西,它将返回 false。 这是我的代码:
public static boolean isPositiveInteger(String input) {
int stringLength = input.length();
int index = stringLength-1;
while(index>0) {
index--;
if(input.charAt(0) != '-' && input.charAt(index) >= '0' &&
input.charAt(index) <= '9') {
return true;
}
return false;
}
return false;
}
当输入是字符串“fish33”时,该方法将返回 true 而不是 false。 这是为什么?
您的while
循环只执行一次 - return
将停止执行。 此外,您从倒数第二个开始,而不是从最后一个字符开始。 用这个替换你的代码:
public static boolean isPositiveInteger(String input) {
int stringLength = input.length();
int index = stringLength;
// special case when input is empty string
if (index == 0) {
return false;
}
while(index > 0) {
index--;
// if some of the characters is not digit, return false
if !(input.charAt(index) >= '0' &&
input.charAt(index) <= '9') {
return false;
}
}
// if the while loop does not find any other character, return true
return true;
}
做这么多操作没有意义,几行就可以解决
public static void main(String[] args) {
System.out.println(isPositiveInteger("1"));
System.out.println(isPositiveInteger("abc"));
}
public static boolean isPositiveInteger(String input) {
try {
Integer i = Integer.parseInt(input);
return i > 0;
}
catch(NumberFormatException nfe){
return false;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.