Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Repeating Java Array

Tags:

java

arrays

loops

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!

like image 245
GiantDwarf Avatar asked May 09 '13 17:05

GiantDwarf


People also ask

How do you repeat an array loop in Java?

You can loop through the array elements with the for loop, and use the length property to specify how many times the loop should run.

Can array have duplicate values in Java?

All you need to know is that Set doesn't allow duplicates in Java. Which means if you have added an element into Set and trying to insert duplicate element again, it will not be allowed. In Java, you can use the HashSet class to solve this problem.

How do you check if a number is repeated in an array?

To check if an array contains duplicates: Use the Array. some() method to iterate over the array. Check if the index of the first occurrence of the current value is NOT equal to the index of its last occurrence. If the condition is met, then the array contains duplicates.


1 Answers

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';
    }
}
like image 184
Jon Skeet Avatar answered Oct 28 '22 00:10

Jon Skeet