在if语句中检查两个条件

问题描述

我正在检查2个条件,我需要它们都可以工作, 但只工作其中之一。我在哪里犯错?我需要在字符串文本中打印ch1和ch2的位置索引

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;
  }
}

解决方法

如果我理解正确,您想知道char1和char2的位置。

您编写逻辑的方式只能返回一个值。

您需要删除return语句并将结果收集到某个变量中。

然后在末尾返回该变量。

或类似的方法应该起作用:

  public class TestIndexOf {
    
       // private static String text;
       // private  static char ch1,ch2;
    
      public static void printIndex(String text,char ch1,char ch2) {
            int count = 0;
            boolean isCharAIndexNotPrinted = true;
            boolean isCharBIndexNotPrinted = true;
            for (int i = 0; i < text.length(); i++) {
              if(count==2)
                 break;
              if (text.charAt(i) == ch1 && isCharAIndexNotPrinted) {
                count++;
                isCharAIndexNotPrinted = false;
                System.out.println("char1 is " + i);
              }
               if (text.charAt(i) == ch2 && isCharBIndexNotPrinted) {
                count++;
                isCharBIndexNotPrinted = false;
                System.out.println("char2 is " + i);
              }
          }
      }
    }