Java array repetition

I am new to java and still learning, so keep that in mind. I am trying to write a program in which the user can enter a keyword, and he converts it into numbers and puts in an array. My problem is that the array should keep repeating int.

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 keyword.length , it throws an outofbounds error. I need it to be small.

Basically, if keyword.length() was 3, I need to be able to see that key[2] matches key[5] and key[8] , etc.

Thank you for your help!

+8
java arrays loops
source share
1 answer

Well, the easiest way to fix your code first is through refactoring. 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 problem 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'; } } 

Suppose you really make key longer than keyword - and you probably want to change the top 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'; } } 
+4
source share

All Articles