数组索引越界项目Euler问题17

时间:2019-04-10 21:05:44

标签: java arrays string

我目前陷入欧拉计划中的问题17。一点背景:我的程序对于1-120很好用。一旦超过120,就不会按照我的意图使用模运算符。我正在尝试解决此问题,但对于该问题的先前迭代,除法和余数函数均能正常工作,因此我试图找出导致条件错误的更改(I> = 120 && I < 1000)(P,不要在意优化,我是一名编程学生,只是致力于创建数组并适应数组)。谢谢!

我尝试在不同时间使用除法和余数运算符,例如(I> = 120 && I <1000)上的s + = ones [division(I)],但尚未解决错误。 / p>

public class LetterCount {

    public static void main(String[] args) {
        int i;
        String[] ones = {"","one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten","eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen", ""};
        String[] tens = {"", "","twenty", "thirty", "fourty", "fifty", "sixty", "seventy", "eighty", "ninety", ""};
        String[] hundreds = {"","onehundred", "twohundred", "threehundred", "fourhundred", "fivehundred", "sixhunded", "sevenhundred", "eighthundred", "ninehundred"};
        String[] thousand = {"", "onethousand"};
         String s  = new String();
         for(i = 0; i <= 126; i++) {
             if(i <= 20) {
                 s+= ones[i];
             }
             if(i == 20) {
                 //performs i / 10
                 s+= tens[division(i)];
             }
             if(i > 20 && i < 100) {
                 //performs i / 10 & i % 10
                 s+= tens[division(i)];
                 s+= ones[remainder(i)];
             } if (i == 100) {
                 //performs i / 100
                 s+= hundreds[division(i)];
             } if (i > 100 && i < 120) {
                 //performs i / 10, i % 10, and i / 100
                 s+= hundreds[division(i)];
                 s+= tens[division(i)];
                 s+= ones[remainder(i)];

             } if (i >= 120 && i < 1000) {
                 //performs i / 100, i / 10, and i % 10
                s+= hundreds[division(i)];
                s+= tens[division(i)];
                s+= ones[remainder(i)];


             } if (i == 1000) {
                 s+= thousand[division(i)];
             }
         }
         System.out.println(s);
    }

    public static int remainder(int i) {
        if (i >= 100 && i <= 1000) {
            return i % 100;
        } else if(i > 10 && i < 100) {
            return i % 10;
        }
        return i;
    }
    public static int division(int i) {
        if (i == 1000) {
        return i / 1000;
        } 
        if (i >= 100 && i <= 1000) {
            return i / 100;
        } if (i < 100)  {
            return i / 10;
        }
        return i;
    }
}

1 个答案:

答案 0 :(得分:1)

您的ones数组 length = 21
因此,您可以访问的最后一个元素将是ones[20]
但是在函数remainder(int i)中,您最多可以返回 99
的值 因为您的方法包含这一行return i % 100;
因此,何时使用ones[remainder(i)];
如果返回的提醒值> 20

,您通常会面对Array Index Out of Bounds