string - how to take char input before int input in java? -
public class pack1 { public static void main(string ar[]) throws ioexception { bufferedreader br = new bufferedreader(new inputstreamreader(system.in)); system.out.println("enter character"); char c=(char)br.read(); system.out.println(c); system.out.println("enter integer"); long l=integer.parseint(br.readline()); system.out.println("long l="+l); system.out.println(c); } }
let's user types x
, presses enter on first question, types 123
, presses enter on second question, mean input stream contains following characters:
x <cr> 1 2 3 <cr>
when call read()
, read x
. when call readline()
, read <cr>
, blank string back.
the 1 2 3 <cr>
still sitting unread in input stream.
solution: call readline()
after reading x
skip past rest of line, or use readline()
read x
string
, instead of char
.
fyi: exact same problem people keep having when using scanner
, mixing calls nextline()
calls other nextxxx()
methods, nextint()
.
Comments
Post a Comment