java字符在字符串中的位置

java字符在字符串中的位置,java,string,position,character,Java,String,Position,Character,我希望SO能帮我解决这个问题。我有以下代码: public static void main(String[] args) { Scanner scanner=new Scanner(System.in); System.out.print("Enter a string:\t"); String word = scanner.nextLine(); System.out.print("Enter a character:\t"); String ch

我希望SO能帮我解决这个问题。我有以下代码:

public static void main(String[] args) {
    Scanner scanner=new Scanner(System.in);

    System.out.print("Enter a string:\t");
    String word = scanner.nextLine();

    System.out.print("Enter a character:\t");
    String character = scanner.nextLine();

    char charVar = 0;
    if (character.length() > 1) {
        System.err.println("Please input only one character.");
    } else {
        charVar = character.charAt(0);
    }

    int count = 0;
    for (char x : word.toCharArray()) {
        if (x == charVar) {
            count++;
        }
    }

    System.out.println("Character " + charVar + " appears " + count + 
                       (count == 1 ? " time" : " times"));
}

这段代码要求用户输入一个字符串,然后要求用户输入一个字符,然后程序会告诉用户该字符出现了多少次。我的问题是,我需要转换这段代码,这样它仍然会要求用户输入字符串,但不会要求输入字符。它将要求用户输入一个数字。然后程序将显示字符串中该位置的字符。示例:假设输入“string”,然后输入2作为数字,程序将显示字符“r”。所以我的问题基本上是,是否有人能给我一个如何实现这一目标的想法。任何帮助都会很好。

好吧,你可以从不再忽略其他问题的帖子开始,请参考代码的来源,或者更好,只包含你的代码。使用scanner.nextInt()获取整数,然后使用String.charAt(int)从指定字符串中获取该索引处的字符。缩进使代码可读。你应该试试。@Brunaido你能不能进一步解释一下你的评论,当我这么做的时候,它说“不能静态引用非静态方法”。谢谢你的回答。完全不相关的问题,如果你在程序中从不关闭扫描仪,问题有多大?在这里的一个简单的例子中,它只是读取用户输入,这不是问题,除非我们要读取更多输入。当然,如果我们正在打开和读取文件或其他资源,这可能会成为一个问题(损坏文件等)。但是,使用后不需要关闭它,Java环境会在程序终止时自动关闭它。
public static void main(String[] args) {
        Scanner scanner=new Scanner(System.in);

        System.out.print("Enter a string:\t");
        String word = scanner.nextLine();

        System.out.print("Enter an integer:\t");
        int index = scanner.nextInt();

        System.out.println("Character at position " + index + ": " + word.charAt(index));
    }