Why string inputs after integer input gets skipped in Java? -
this question has reply here:
scanner issue when using nextline after nextxxx [duplicate]i trying input values of string , integer variables in java. if taking input of string after integer, in console string input skipped , moves next input.
here code
string name1; int id1,age1; scanner in = new scanner(system.in); //i can input name if input before integers system.out.println("enter id"); id1 = in.nextint(); system.out.println("enter name"); //problem here, name input gets skipped name1 = in.nextline(); system.out.println("enter age"); age1 = in.nextint();
this mutual problem, , happens because nextint method doesn't read newline character of input, when issue command nextline, scanner finds newline character , gives line.
a workaround one:
system.out.println("enter id"); id1 = in.nextint(); in.nextline(); // skip newline character system.out.println("enter name"); name1 = in.nextline(); another way utilize nextline wrapped integer.parseint:
int id1; seek { system.out.println("enter id"); id1 = integer.parseint(input.nextline()); } grab (numberformatexception e) { e.printstacktrace(); } system.out.println("enter name"); name1 = in.nextline(); why not scanner.next() ? i not utilize scanner.next() because read next token , not total line. illustration next code:
system.out("enter name: "); string name = in.next(); system.out(name); will produce:
enter name: mad scientist mad it not process scientist because mad completed token per se. maybe expected behavior application, has different semantic code posted in question.
java
No comments:
Post a Comment