BufferedReader values into char array
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?
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.
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)
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.
You can also read all characters at once in the array by using provided methods in the Reader public interface.
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);
I hope this helps I would add all inputs into one string and then use toCharArray()
characters into array (efficient)
Character[] charArray = br.readLine().toCharArray();
characters into array (inefficient)
Character[] charArray = Arrays.stream(br.readLine().split("")).map(str->str.toCharArray()[0]).toArray(Character[]::new);
characters into list
List<Character> charList= Arrays.stream(br.readLine().split("")).map(str->str.toCharArray()[0]).collect(Collectors.toList());
精彩评论