2014-09-30 35 views
0

我想創建一個方法,它接受用戶輸入的數字,測試數字中的每個數字是否爲奇數,如果全部都是奇數則返回真,如果全部都是偶數則返回假。繼承人的代碼。爲什麼有些值即時獲取錯誤,但其他人不是?

public static boolean allDigitsOdd(int num){ 

    int digits[] = new int[10]; 
    int numDigits = 0; 
    String numTemp = Integer.toString(num); 

    while(num > 1){ 
     num = num/10; 
     numDigits++; 
    } 
    numDigits++; 

    for(int i = 0; i < numDigits; i++){ 
     digits[i] = numTemp.charAt(i) - '0'; 
     System.out.println(digits[i]); 
    } 

    for(int i = 0; i < numDigits; i++){ 
     if(digits[i] % 2 == 0){ 
      return(false); 
     } 
     if(i == numDigits){ 
      return(true); 
     } 
    } 
    return(true); 
} 

當我輸入「1234」或「1357」,它的偉大工程,並返回正確的布爾但是當我鍵入幾乎任何東西,它給了我一個「字符串索引超出範圍」的錯誤在

digits[1] = numTemp.charAt(i) - '0'; 
+0

你可能想檢查負數? – 2014-09-30 13:16:27

+0

如果有奇數和偶數混合會怎麼樣?它必須返回什麼? – 2014-09-30 15:16:54

回答

1

更改while(num > 1)while(num >= 10)

否則,它只適用於以1開頭的數字(如1234和1357),因爲對於以2到9開頭的數字(例如9436534或4334),您的numDigits的計算將會過高一個,導致'字符串索引超出範圍'。

忘記numDigits會更好,只是用numTemp.length()代替。

+0

而不是while循環,Jason可以使用numTemp.length() – 2014-09-30 13:14:47

+0

@VimalBera我的記憶背叛了我。我確信String有一個size()方法,而不是length()。 :) 謝謝! – Eran 2014-09-30 13:17:08

+0

哈哈@Eran。同樣的事情發生在我身上,然後我找到了記住的方式。字符串總是可以測量長度,如釐米,米等。希望這可以幫助你:D – 2014-09-30 13:21:05

0

我會以另一種方式解決這個問題。

而不是把你的號碼變成一個字符串(這可能會給你科學記數法值和/或千位分隔符等)砍掉最後一位數字併除以10給你一個新的數字,像這樣(遞歸!):

public static boolean allDigitsOdd(int num){ 

    if (num < 0) { 
     throw new IllegalArgumentException("num must be 0 or positive"); 
    } 

    if (num < 10) { // for 0-9, this is easy 
     return (num % 2 != 0); // if it isn't even, it's odd 
    } else { // here comes the fun part 
     int lastDigit = num % 10; // % is the remainder operation, not the modulo operation 
     int newNum = num/10; // because this is how ints work, this chops off the last digit 
     return (lastDigit % 2 != 0) && allDigitsOdd(newNum); // recursion fun! 
     // This will only return true if all of the tested digits are odd; 
     // If there is just one even digit, the && operator returns false 
    } 
} 

System.out.println(allDigitsOdd(1242)); // false 
System.out.println(allDigitsOdd(73335799)); // true 

您可以用二元運算符做到這一點,但只是使得它的可讀性,而不是更快了。

0

你甚至可以把所有的東西變成一個簡單的循環:

public static boolean allDigitsOdd(int num) 
{ 
    while(num != 0) 
    { 
     if(num % 2 == 0) 
      return false; // last digit is even 
     num /= 10; // cut of last digit and repeat 
    } 
    return true; // all digits were odd 
} 

這甚至負數工作!

相關問題