Skip to content
Advertisement

how to get first character of a second word in java

Im currently working through my first java course and trying to write a program that asks the user to type a word then it returns the first letter of that word. then the programs asks the user for a second word and returns the first Charecter of that word. so if the first word is apple it returns “a” and then the if next word is banana it returns “b”.

im using the next char method but once give the user the prompt”write a second word” and call the next char the computer doesn’t wait for the user to type a line it just takes the second character from the first word and prints it. really appreciate any help this one has got me totally baffled.

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

Advertisement

Answer

I think it’s better to read the whole string first, and then get the first character of it.

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

Output:

type a word: apple
The first letter is 'a'
type a word: bannana
The first letter is 'b'

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement