vendredi 21 août 2020

check two conditions in if statement [closed]

I am checking for 2 conditions, and I need that both of them would work, but work only one of them. Where I am making the mistake? I need to print indexes of positions of ch1 and ch2 in String text

import java.util.Scanner;

public class TestIndexOf {

    private static String text;
    private  static char ch1, ch2;

    public static void main(String[] args) {
        TestIndexOf  test = new TestIndexOf();
        test.getInput();
        System.out.println(test.getIndex(text, ch1, ch2));
    }

    public static void getInput() {
        Scanner scan = new Scanner(System.in);
        System.out.println("Enter word and chars: ");
        text = scan.nextLine();

        ch1 = scan.next().charAt(0);
        ch2 = scan.next().charAt(0);

    }

    public static int getIndex(String text, char ch1, char ch2) {
        for (int i = 0; i < text.length(); i++) {
          if (text.charAt(i) == ch1) {
            return i;
           }
          if (text.charAt(i) == ch2) {
             return i;
          }
        }

      return -1;
  }
}

Aucun commentaire:

Enregistrer un commentaire