【问题标题】:How do I read a single character from a Scanner?如何从扫描仪读取单个字符?
【发布时间】:2023-03-24 17:22:01
【问题描述】:

我有一个字符列表,我想在用户输入字符时将每个字符添加到列表中(键盘是扫描仪)。我尝试了两种不同的方法,但都不起作用:

char temp = keyboard.nextByte();
charList.add(temp);

charList.add(keyboard.nextBye();

那我该怎么办呢?

【问题讨论】:

  • 您可以使用nextLine 并遍历字符串的每个字符并将其插入到列表中。
  • 标题具有误导性。这与 ArrayList 无关。应该是“如何从扫描仪中读取单个字符?”
  • 您不会在用户键入时获得字符。您可以使用 next,获取一个字符串,然后从该字符串中获取所有字符。

标签: java char character


【解决方案1】:

如果你只想接受一个字符输入

char temp keyboard.next().charAt(0);
charList.add(temp);

始终使用第二个,因为您不知道用户可能会输入字符串。因此,第二个对两者都有效。

【讨论】:

  • next() 总是返回一个字符串。
【解决方案2】:

我们这个 扫描仪阅读器 = new Scanner(System.in);

char c = reader.nextChar();

您可以从 Scanner.next 中获取第一个字符:

char c = reader.next().charAt(0);

要使用您可以使用的一个字符:

char c = reader.findInLine(".").charAt(0);

要严格使用您可以使用的一个字符:

char c = reader.next(".").charAt(0);

【讨论】:

  • Scanner.nextChar 不存在。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-02-22
  • 1970-01-01
  • 2016-06-20
  • 2012-12-06
  • 1970-01-01
相关资源
最近更新 更多