java BufferedReader 值转换为字符数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5694998/
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
BufferedReader values into char array
提问by paul
char charArray[] = new char[ 100 ];
BufferedReader buffer = new BufferedReader(
new InputStreamReader(System.in));
int c = 0;
while((c = buffer.read()) != -1) {
char character = (char) c;
How do I put the entered characters into my array?
如何将输入的字符放入数组?
回答by Hyman
Use the correct method which does exactly what you want:
使用正确的方法,它完全符合您的要求:
char[] charArray = new char[100];
BufferedReader buffer = new BufferedReader(new InputStreamReader(System.in));
int actualBuffered = buffer.read(charArray,0,100);
As stated in documentation here, this method is blocking and returns just when:
正如文件指出这里,这种方法被阻塞,并返回正当:
- The specified number of characters have been read,
- The read method of the underlying stream returns -1, indicating end-of-file, or
- The ready method of the underlying stream returns false, indicating that further input requests would block.
- 已读取指定数目的字符,
- 底层流的read方法返回-1,表示文件结束,或者
- 底层流的 ready 方法返回 false,表明进一步的输入请求将被阻塞。
回答by MeBigFatGuy
You will need another variable that holds the index of where you want to put the variable in the array (what index). each time thru the loop you will add the character as
您将需要另一个变量来保存要在数组中放置变量的位置的索引(什么索引)。每次通过循环时,您都会将角色添加为
charArray[index] = character;
and then you need to increment the index.
然后你需要增加索引。
you should be careful not to write too much data into the array (going past 100)
您应该小心不要将太多数据写入数组(超过 100)
回答by Vincent Ramdhanie
char charArray[] = new char[ 100 ];
int i = 0;
BufferedReader buffer = new BufferedReader(
new InputStreamReader(System.in));
int c = 0;
while((c = buffer.read()) != -1 && i < 100) {
char character = (char) c;
charArray[i++] = c;
}
Stop when you read 100 characters.
读到 100 个字符时停止。
回答by Edwin Dalorzo
You can also read all characters at once in the array by using provided methods in the Reader public interface.
您还可以使用 Reader 公共接口中提供的方法一次读取数组中的所有字符。
char[] input = new char[10];
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
int size = reader.read(input);
System.out.println(String.valueOf(input, 0, size));
System.exit(0);