這是我的任務。我不知道如何實現這個方法。我該如何實現我的parseInt(String str)方法?
實現一個Integer parseInt(String str)的方法throws NumberFormatException將使用輸入字符串,該字符串必須包含唯一數字並且不從零開始,並返回一個數字,該數字必須從該行的轉換中獲得。不允許使用默認類Java的方法。 這就是我如何解決它:
公共類帕爾斯{
public static void main(String[] args) {
String s = " ";
int res = 0;
int[] arr = new int[s.length()];
try {
for (int i = 0; i < s.length(); i++) {
arr[i] = s.trim().charAt(i);
}
try {
for (int i = arr.length - 1, j = 1; i >= 0; i--, j *= 10) {
if ((arr[0] - 48) <= 0 || (arr[i] - 48) >= 10) {
throw new NumberFormatException();
} else {
res += (arr[i] - 48) * j;
}
}
System.out.println(res);
} catch (NumberFormatException n) {
System.out.println("Enter only numbers .");
}
} catch (StringIndexOutOfBoundsException str) {
System.out.println("Don't enter a space!");
}
}
}
理想情況下,您應該先嚐試一下,然後發佈代碼,如果您遇到一些問題。否則,你一定會得到一些反對票。 – Buddha
我試過了。然後它在我身上曙光) –