【问题标题】:Using chars, created by a scanner使用由扫描仪创建的字符
【发布时间】:2014-05-04 17:55:39
【问题描述】:

我正在尝试用 Java 制作一个基本的文本游戏。我决定只在控制台上制作游戏,因为这是我知道的唯一方法。我正在尝试使用 chars 来查看用户键入的内容是否在位置 0 处包含字母 h,当我在 main 方法中尝试它时它工作正常,但当我将它作为单独的方法调用时它不起作用。

    import java.util.Scanner;



    public class testing
    {

static Scanner kb = new Scanner(System.in);

public static void main(String[] args)
{
    System.out.println("Wanna start the game?");
    System.out.println("1. Start");
    System.out.println("2. Quit");
    int ans = kb.nextInt();

    if(ans == 1)
    {
        levelOne();
    }

    else
        System.out.println("Quitting");
}

public static void levelOne()
{
    System.out.println("Type something");
    char letter = kb.nextLine().charAt(0);
    if(letter == 'h')
    {
        System.out.println("contains h");
    }
    else
        System.out.println("does not contain h");
}

}

【问题讨论】:

    标签: java methods char


    【解决方案1】:

    因为nextInt 不使用任何非数字输入,您需要在调用nextLine 之前使用方法传递的换行符

    kb.nextLine(); // added
    char letter = kb.nextLine().charAt(0);
    

    【讨论】:

    • 对这取决于程序的合同。 OP 没有得到任何异常 否则StringIndexOutOfBoundsException 被捕获。
    【解决方案2】:

    先去掉空格再获取字符

    char letter = kb.nextLine().trim().charAt(0);
    

    输入1 hello

    注意hello之前的空格

    输出:

    Wanna start the game?
    1. Start
    2. Quit
    1  hello
    Type something
      hello
    does not contain h
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多