Reputation: 21
I'm currently stuck on problem 17 in Project Euler. a little background: My program works fine for numbers 1- 120. once I get past 120, its not using the modulo operator in the way I've intended. I'm trying to fix it, but for previous iterations of this problem, the division and remainder functions are working correctly, so I'm trying to figure out what's changed that's causing an error on the conditional (I >= 120 && I < 1000)(Ps, don't care about optimizing, I'm a programming student and just working on creating and getting comfortable with arrays). thanks!
I've tried using my division and remainder operators at different times, such as s+= ones[division(I)] on the (I >= 120 && I < 1000) conditional and haven't fixed the error.
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;
}
}
Upvotes: 0
Views: 68
Reputation: 19036
Your ones
array length = 21
So the last element you can access it will be ones[20]
But in your function remainder(int i)
, you can return values up to 99
Because your method contains this line return i % 100;
So when you will use ones[remainder(i)];
You will face Array Index Out of Bounds
normally if the returned reminder value > 20
Upvotes: 2