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!
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.
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.
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.
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';
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With