-1

I am trying to get my string letters to show me the index for every letter given as input. For example when I input a it returns 0 which is the index. Currently if I input a word with letter a and b it wont return anything. But it should return 0 and 1.

String[] code = {"a", "b","c", "d", "e"};

String letters=input.nextLine();

for (int i=0;i<code.length;i++) {
    if (letters.equals(code[i])) {
        System.out.print(i);
    }
}
Juan Carlos Mendoza
  • 5,736
  • 7
  • 25
  • 50
Lori wayne
  • 35
  • 5

5 Answers5

2

You have to treat both elements the same way, as in:

for (char charFromUser : letters.toCharArray()) {
  for (int i=0; i < code.length; i++) {
    if (code[i] == charFromUser) {
      ... print i

In other words: you intend to compare characters, one by one. Then using equals() on the complete string given by the user doesn't help you.

GhostCat
  • 137,827
  • 25
  • 176
  • 248
0

You'll need to loop through your input character by character in order to return more than one letter's index number

Paul Brittain
  • 319
  • 2
  • 17
0

Try somethink like this :

char[] List={'a','b','c','d'};

int count=0;
for(int i=0;i<List.length;i++){
    for (int j=0;j<input.length();j++) {
        if(input.charAt(j)==List[i]){
            count++;
        }
    }
}
System.out.println(count);
Léo R.
  • 2,620
  • 1
  • 10
  • 22
0

you can try with this agine

public class StringTest {
    public static void main(String[] args) {
        String[] code = {"a", "b", "c", "d", "e"};

        Scanner input = new Scanner(System.in);
        while (true) {
            System.out.printf("please input:");
            String letters = input.nextLine();
            boolean isMatch = false;
            for (int i = 0; i < code.length; i++) {

                if (letters.equals(code[i])) {
                    isMatch = true;
                    System.out.println(i);
                }
            }

            if (!isMatch) {
                System.out.println("not equal");
            }

        }
    }
}
jack
  • 1
  • 2
0

As @GhostCat answered, you are not comparing the characters in your input one by one with the values in your array. Another alternative is to use the built-in String::indexOf method to get this even easier:

String code = "abcde";
String letters = input.nextLine();

for (char c : letters.toCharArray()) {
    System.out.print(code.indexOf(c));
}
  • Input >> ab
  • Output >> 01
Juan Carlos Mendoza
  • 5,736
  • 7
  • 25
  • 50