Reputation: 33
I'm trying to take a string as an input (around 5 - 7 characters), iterate through each character and check whether or not it matches a character from an array. For example:
static String Registration(String reg) {
int[] numbers = {0, 1, 2, 3, 4, 5, 6, 7 , 8, 9,};
if (reg.length() >= 7) {
for (int i = 0; i < reg.length(); i++) {
reg.indexOf(numbers[i]);
}
}
}
The above is clearly wrong. However, I hope it illustrates what I'm trying to do. For example, if the string was "H3llo", I would want to check each character in the string and see if it matches with any items in the array. If it does, I would like to store the index as an int.
This is probably not an efficient way of doing it, but it's the only way I can think of with my current level of learning.
Upvotes: 0
Views: 78
Reputation: 68
there are several problems with your code here:
numbers
array is of type int, however you want to compare the characters. use char[] instead and use chars in your array instead of ints like this: '0', '1', ...
public String Registration
but you want to return an int. change this to public int Registration
.return
in your function if your function should return something.A possible solution may look like this:
public static int Registration(String reg) {
char[] numbers = {'0', '1', '2', '3', '4', '5', '6', '7' , '8', '9',}; // use a char array char[] and add numbers as chars to array.
if (reg.length() >= 7) {
for (int i = 0; i < reg.length(); i++) {
char character = reg.charAt(i);
for(char number : numbers)
{
if(number == character)
{
return i; // found a matching character, return the index of the matching character
}
}
}
}
// return -1 for the case that we find nothing.
return -1;
}
please try to understand what happens here and do not just copy and paste the solution.
Note: the thing you wish to do can be easily implemented with RegEx, however, this may be too hard for you at your current stage.
Upvotes: 1