我想通過一個字符串循環,並檢查每個字符,如果其中一個字符是一個數字。如果它是一個數字,我想把它作爲真實返回。我有一個字符串「崩潰」,雖然它返回它爲真(它有一個數字)。檢查每個字符的數字
這是我到目前爲止有:
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;
}
我無法弄清楚什麼是錯的。我的邏輯似乎很好,但我的編碼不是。
編輯:我想通了。感謝你的幫助!
更好的方式來做到這一點是使用['的Integer.parseInt()'](http://download.oracle。 com/javase/1.4.2/docs/api/java/lang/Integer.html#parseInt(java.lang.String%29)嘗試將字符串解析爲一個int,然後看看是否有效 – NullUserException
我試着運行代碼,它給了我正確的答案...假...你可以發佈你正在使用的代碼來測試這個函數 – jsshah
奇怪...我試着運行它,它出現了錯誤! – Mindgames