因此,我试图制作一个布尔方法,检查输入的字符串是否为正整数。如果它是一个正整数,它将返回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。那是为什么?
答案 0 :(得分:1)
您的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;
}
答案 1 :(得分:-1)
没有必要进行如此多的操作,可以用几行来解决
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;
}
}