繁体   English   中英

通过JAVA中的“For”循环使用“Scanner”和“charAt(0)”读取第一个输入字符

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

我试图通过提供一个单词来获取第一个字符。

例如

输入一个词:苹果

第一个字符是“a”

进入一个世界:香蕉

第一个字符是“b”

当我执行代码(下面提供)时,第一个循环使用charAt(0)提供正确的结果,但下一个循环的结果将给出“空”字符。 (即我通过应用charAt(1)得到正确的结果)

我不知道这个空字符是什么(换行?制表符?空格?),也不知道如何删除这个字符。

并且没有必要在循环内重复声明每个 Scanner 字段。

PS 我试过应用分隔符(例如useDelimiter(System.lineSeparator())或删除前导和尾随空格(例如trim() ),但结果是一样的。

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

    }

}

预期结果

输入一个词:苹果

第一个字符是“a”

输入一个词:香蕉

第一个字符是“b”

输入一个词:橙色

第一个字符是“o”

....

实际结果

输入一个词:苹果

第一个字符是“a”

输入一个词:香蕉

第一个字符是“”

输入一个词:橙色

第一个字符是“”

....

我试过你的代码。 大多数部件工作正常。

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

}

结果 :

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"

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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