8

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!

2
  • not ++k, but k+=keyword.length(); Commented May 9, 2013 at 18:02
  • Is it intentional, that you leave some elements in key to 0? Commented May 9, 2013 at 18:11

1 Answer 1

4

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';
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.