检查if语句中的两个条件

toiithl6  于 2021-07-08  发布在  Java
关注(0)|答案(1)|浏览(249)

**结束。**此问题需要详细的调试信息。它目前不接受答案。
**想改进这个问题吗?**更新问题,使其成为堆栈溢出的主题。

5个月前关门了。
改进这个问题
我正在检查两个条件,我需要他们都将工作,但只工作其中一个。我在哪里犯错?我需要打印字符串文本中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;
  }
}
g6baxovj

g6baxovj1#

如果我理解正确,你想知道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);
              }
          }
      }
    }

相关问题