java java中的nextChar()

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5012113/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 09:03:29  来源:igfitidea点击:

nextChar() in java

javacharjava.util.scanner

提问by hedgehogrider

If I'm taking input with a scanner and I want to put a single character into a char type variable, what is the most efficient algorithm? I just noticed that both next() and nextLine() return strings regardless of the size, and aside from getting a string, casting it into a char array and then taking the first element, I can't think of how I would do this. There must be a more efficient way!

如果我使用扫描仪输入并且想将单个字符放入 char 类型变量中,那么最有效的算法是什么?我只是注意到 next() 和 nextLine() 无论大小都返回字符串,除了获取字符串,将其转换为 char 数组然后获取第一个元素之外,我想不出我将如何做到这一点. 必须有更有效的方法!

回答by jluzwick

You could use FileChannelto create a ByteBuffer. Once here you can then call the asCharBuffer()method to return a char buffer.

您可以使用FileChannel创建一个ByteBuffer. asCharBuffer()到达此处后,您可以调用该方法以返回字符缓冲区。

Here's a decent example: Example using CharBuffers

这是一个不错的例子: Example using CharBuffers

回答by Bhanu

To read a character from input you can use the builtin function char charAt():

要从输入中读取字符,您可以使用内置函数char charAt()

import java.util.Scanner;
Scanner sc = new Scanner(System.in); 
char c = sc.next().charAt(0)