[英]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.