简体   繁体   中英

Read the fist input character using "Scanner" and "charAt(0)" through the "For" loop in JAVA

I am trying to obtain the first character by providing a word.

eg

Enter a word: apple

The first character is "a"

Enter a world: banana

The first character is "b"

When I execute the code (provided below), the first loop provides the correct result with charAt(0) but the consequences of next loops would gives the "Empty" character. (ie I get correct result by applying charAt(1) )

I have no clue what this empty character is (new line? tab? white space?) and do not no how to remove this one.

And it would be unnecessary to declare every Scanner field repeatedly inside the loop.

PS I have tried with applying delimiter (eg useDelimiter(System.lineSeparator()) or remove the leading & tailing spaces (eg trim() ) but the result would be the same.

import java.util.Scanner;

public class ReadCharacter {

    // Declare the scanner field
    private static Scanner input;

    public static void main(String[] args) {

        input = new Scanner(System.in);

        // Prompt the user to enter character
        for (int i = 0; i < 5; i++) {

            System.out.print("Enter a word: ");
            char character = input.next().charAt(0);    

            // Show the result
            System.out.println("The first character is \"" + character + "\"\n");           
        }

    }

}

Expected result

Enter a word: apple

The first character is "a"

Enter a word: banana

The first character is "b"

Enter a word: orange

The first character is "o"

....

Actual Result

Enter a word: apple

The first character is "a"

Enter a word: banana

The first character is ""

Enter a word: orange

The first character is ""

....

I tried your code. The most parts work properly.

public static void main(String[] args) {
    //change in this answer
    Scanner input = new Scanner(System.in);

    // Prompt the user to enter character
    for (int i = 0; i < 5; i++) {

        System.out.print("Enter a word: ");
        char character = input.next().charAt(0);

        // Show the result
        System.out.println("The first character is \"" + character + "\"\n");
    }

}

Result :

Enter a word: apple
The first character is "a"

Enter a word: orange
The first character is "o"

Enter a word: banana
The first character is "b"

Enter a word: nothing
The first character is "n"

Enter a word: wrong
The first character is "w"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM