2
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?

5 Answers 5

8

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.
Sign up to request clarification or add additional context in comments.

1 Comment

This is nice, since unlike the normal stream contract, BufferedReader will try to fetch the requested number of characters by reading multiple times from the underlying stream.
0

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)

Comments

0
     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.

1 Comment

Does not stop at all - missing i++.
0

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);

Comments

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());

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.