Reputation: 11
My program is only allowing me to enter 3 characters into the array and not five. Why is that so?
import java.io.*;
public class Prog{
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
char c[] = new char[5];
for(int i=0;i<-4;i++){
c[i]= (char) br.read();
}
}
}
Upvotes: 1
Views: 29
Reputation: 522762
From the Javadoc for BufferedReader#read():
Reads a single character
In other words, this will read in each character one by one. The reason it appears that you can only enter three characters is because you are pressing enter after each character:
first character
ENTER
second character
ENTER
third character
Use readLine()
:
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
char c[] = new char[5];
for (int i=0; i<=4; i++) {
c[i] = br.readLine().charAt(0);
}
}
This approach will read in one line at a time, in this case a line being defined as a single character followed by a newline. If you enter more than one character in a given line input, then only the first one will be used.
Upvotes: 2