数组索引超出界限项目欧拉问题17

问题描述 投票:0回答:1

我目前在Project Euler中遇到问题17。一点背景:我的程序适用于数字1- 120.一旦我超过120,它不按照我的意图使用模运算符。我正在尝试修复它,但是对于此问题的先前迭代,除法和余数函数正常工作,所以我试图找出导致条件错误的更改(I> = 120 && I < 1000)(Ps,不关心优化,我是一名编程学生,只是致力于创建和熟悉数组)。谢谢!

我尝试在不同的时间使用我的除法和余数运算符,例如s + = [division(I)]对(I> = 120 && I <1000)条件并且没有修复错误。

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;
    }
}
java arrays string
1个回答
1
投票

你的ones数组长度= 21 所以你可以访问它的最后一个元素是ones[20] 但是在你的函数remainder(int i)中,你可以返回最多99的值 因为你的方法包含这行return i % 100; 所以当你使用ones[remainder(i)];时 如果返回的提醒值> 20,您将正常面对Array Index Out of Bounds

© www.soinside.com 2019 - 2024. All rights reserved.