如何在java中获取第二个单词的第一个字符

如何在java中获取第二个单词的第一个字符,java,Java,我目前正在学习我的第一门java课程,试图编写一个程序,要求用户键入一个单词,然后返回该单词的第一个字母。然后程序要求用户输入第二个单词,并返回该单词的第一个字符。因此,如果第一个单词是苹果,它会返回“a”,如果下一个单词是香蕉,它会返回“b” 我正在使用next char方法,但是一旦给用户提示“写第二个单词”并调用下一个字符,计算机就不会等待用户键入一行,它只是从第一个单词中提取第二个字符并打印出来。真的很感谢你的帮助,这一次让我完全困惑 public class FirstAttempt

我目前正在学习我的第一门java课程,试图编写一个程序,要求用户键入一个单词,然后返回该单词的第一个字母。然后程序要求用户输入第二个单词,并返回该单词的第一个字符。因此,如果第一个单词是苹果,它会返回“a”,如果下一个单词是香蕉,它会返回“b”

我正在使用next char方法,但是一旦给用户提示“写第二个单词”并调用下一个字符,计算机就不会等待用户键入一行,它只是从第一个单词中提取第二个字符并打印出来。真的很感谢你的帮助,这一次让我完全困惑

public class FirstAttempt {

    public static void main(String... args) {
        Scanner s = new Scanner(System.in);
        char a;
        char b;

        System.out.println("type a word");
        a = s.findWithinHorizon(".", 0).charAt(0);

        System.out.println(a);


        System.out.println("type a second word");

        b = s.findWithinHorizon(".", 0).charAt(0);

        System.out.println(b);
    }
}

我不认为使用
s.findWithinHorizon
是必要的-你可以使用
s.next()

我认为最好先读取整个字符串,然后获取它的第一个字符

public class FirstAttempt {

    public static void main(String... args) {
        Scanner scan = new Scanner(System.in);
        char a = getNextChar(scan);
        System.out.println("The first letter is '" + a + '\'');
        char b = getNextChar(scan);
        System.out.println("The first letter is '" + b + '\'');
    }

    private static char getNextChar(Scanner scan) {
        System.out.print("type a word: ");
        return scan.next().charAt(0);
    }
}
输出:

type a word: apple
The first letter is 'a'
type a word: bannana
The first letter is 'b'
阅读文档,即javadoc:“如果找到模式,扫描器前进超过匹配的输入”,因为“匹配的输入”是输入的第一个字符,扫描器只前进超过第一个字符,这意味着下次执行时,您将获得第二个字符。该方法所做的正是它被记录下来要做的提示:不要为此使用
findWithinHorizon()