Equality of String characters and usual character don't work / How to get indexes of those chars

旧街凉风 提交于 2021-02-11 12:32:29

问题


I am trying to compare the chars of user String with the 2 chars also got from user, and if one of them is equal to char of that String in particular index, so I need to print that index.

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();
      
        char ch1 = scan.next().charAt(0);
        char 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) == ch1) {
                return i;
            }
        }
        return -1;
    }
}

回答1:


private  static char ch1, ch2;
....
char ch1 = scan.next().charAt(0);

This will not assign to ch1 but create a new variable in the getInput method scope, you need to do like this to get the result you expect.

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



回答2:


Your variables ch1 and ch2 are defined twice. First they are declared as static fields on your class but not initialized. Second, they are declared as local variables of getInput and initialized there, but as local variables they can't be accessed from outside the method.



来源:https://stackoverflow.com/questions/63519087/equality-of-string-characters-and-usual-character-dont-work-how-to-get-indexe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!