public static int getDigit(char character, char letters[] )
{
int digit=0;
for (int i=0;i<=0;i++);
{
for (int j=0; j<(letters[i].length());j++)
{
if (letters[i][j]==character)
{
digit=i;
}
}
}
return digit;
}
where array is LETTERS={("abc"),("def"),("ghi"),("jkl"), ("mno)"),("pqrs"),("tuv"),("wxyz")}; and character could be any alphabet.
I want program to find a character entered and to display the location of that in the string. Eg- If user enters letter "g" then it should display number 3 because it is in 3rd element of array.
Here is a working implementation of what you appear to want. I assume that your letters
array is intended to be a 2D jagged character array. Your original code really only had a few minor issues, mainly in the loop logic.
public static int getDigit(char character, char letters[][]) {
int digit = -1; // return -1 if character not found
for (int i=0;i < letters.length; i++) {
for (int j=0; j < letters[i].length; j++) {
if (letters[i][j] == character) {
digit = i;
i = letters.length;
break;
}
}
}
return digit;
}
public static void main(String args[]) {
char[][] letters = new char[][] {
{ 'a', 'b', 'c' },
{ 'd', 'e', 'f' },
{ 'g', 'h', 'i' },
{ 'j', 'k', 'l' },
{ 'm', 'n', 'o' },
{ 'p', 'q', 'r', 's' },
{ 't', 'u', 'v' },
{ 'w', 'x', 'y', 'z' }};
System.out.println(getDigit('d', letters) );
}
It's not really possible to completely answer you question because it doesn't say what the problem is besides "it doesn't work".
Just skimming the code: you should probably change the line digit=i;
to return i + 1;
because you said it should return 3 if "g" is the third character.
Also, this loop is nonsense for (int i=0;i<=0;i++);
It will run only once ever... Also as @bcsb1001 pointed out in the comments, the semicolon at the end of the loop essentially ends it, so the loop is actually empty! It should be for (int i=0;i<letters.length();i++) {
There might be other issues with this code. You didn't share enough.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.