Reputation: 1207
I wrote a loop, but it doesn't work. It should ask me 4 times for a
and for every a
it should write numbers from 0 to 3. But after asking it writes two numbers. Where is mistake?
My code is
package hra1;
public class Hra1 {
public static void main(String args[]) throws java.io.IOException
{
char a;
int i;
for (i = 0; i < 4; i++)
{
a = (char) System.in.read();
System.out.println(i);
}
}
}
Here is an example of the output:
l
0
1
l
2
3
Upvotes: 1
Views: 95
Reputation: 695
Your code is also reading the newline character('\n')
as you are hitting the enter key('\n')
after every input
('1','2','3' etc).
If you type one character and press enter key,System.in.read()
will read two characters as it also reads the newline character.
Re-factored your code a bit. Enter all the values in one line(do not press enter key until you enter all the values). This will solve your problem.
for (i = 0; i < 4; i++)
{
a = (char)System.in.read();
System.out.println(a);
}
Input 4567
Output
4
5
6
7
The ideone code link is here http://ideone.com/IYcjyX. Hope it helps.
Upvotes: 1
Reputation: 1
System.in is an InputStream - read() reads exactly one byte. Your direct input is more than one byte and so both values are directly read within the first input. The program will try to run again the for loop in order to read the next byte of the input.That's why when you give an input that is more than 1 byte,the system try to read the other bytes and system.out.println will be executed more than 1 times.
Upvotes: 0
Reputation: 116
You are actually providing two inputs that are being read when you enter a number in the terminal. First, your integer (e.g. '1'), then a newline character ('\n') when you hit the enter key.
Another method to achieve what you want is to use the Scanner class, like so:
package hra1;
public class Hra1 {
public static void main(String args[])
throws java.io.IOException
{
int i;
Scanner scanner = new Scanner(System.in);
for (i = 0; i < 4; i++)
{
// Scan the next token of input as an integer
int a = scanner.nextInt();
System.out.println(i);
}
}
}
Upvotes: 0
Reputation: 31290
When you type one character and then press the enter key (<-|), the system delivers two characters to your program; hence 0 and 1 are printed after typing the first 'l' and 2 and 3 after typing the second 'l'.
You might print the codepoint of the character read, e.g.,
for (int i = 0; i < 4; i++){
char a = (char) System.in.read();
System.out.println( Character.getNumericValue( a ) );
}
in the loop to see what is going on.
Upvotes: 1