2014-09-30 21 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 
} 

这甚至负数工作!

相关问题