GiantDwarf
GiantDwarf

Reputation: 111

Repeating Java Array

I'm new to java and still learning, so keep that in mind. I'm trying to write a program where a user can type in a keyword and it'll convert it to numbers and put it in an array. My problem is the array needs to keep repeating the int's.

My code is:

String keyword=inputdata.nextLine();
int[] key = new int[keyword.length()];
for (int k = 0; k < keyword.length(); ++k)
{
    if (keyword.charAt(k) >= 'a' && keyword.charAt(k) <= 'z')
    {
        key[k]= (int)keyword.charAt(k) - (int)'a';
    }
}

Right now if I try to get any key[i] higher than the keyword.length it throws an outofbounds error. I need it to to be infinte.

So basically, if keyword.length() were 3 I need to be able to see if key[2] is the same as key[5] and key[8] and so on.

Thanks for your help!

Upvotes: 8

Views: 157

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1500225

Well, it's easiest to fix your code with a bit of refactoring first. Extract all uses of keyword.charAt(k) to a local variable:

for (int k = 0; k < keyword.length(); ++k)
{
    char c = keyword.charAt(k);
    if (c >= 'a' && c <= 'z')
    {
        key[k] = c'a';
    }
}

Then we can fix the issue with the % operator:

// I assume you actually want a different upper bound?
for (int k = 0; k < keyword.length(); ++k)
{
    char c = keyword.charAt(k % keyword.length());
    if (c >= 'a' && c <= 'z')
    {
        key[k] = c - 'a';
    }
}

That's assuming you actually make key longer than keyword - and you probably want to change the upper bound of the loop too. For example:

int[] key = new int[1000]; // Or whatever
for (int k = 0; k < key.length; ++k)
{
    char c = keyword.charAt(k % keyword.length());
    if (c >= 'a' && c <= 'z')
    {
        key[k] = c - 'a';
    }
}

Upvotes: 4

Related Questions