java - Why isn't the scanner input working? -


so new java programmer , trying figure out why piece of code isn't working. issue having line: "string interests = input.nextline();", skips user's input , jumps next system.out, displays "your profile..." in console before allowing user input data. sorry if it's dumb question, i'm new!

system.out.println("hello, " + name + "! gender?"); string gender = input.nextline(); system.out.println("okay, " + name + ", " + gender + ". now, tell me, age?"); int age = input.nextint(); system.out.println("great! we're done. 3 interests have?"); string interests = input.nextline();  system.out.println("...your profile..."); system.out.println("name: " + name); system.out.println("gender: " + gender); 

put this:

int age = input.nextint(); input.nextline(); system.out.println("great! we're done. 3 interests have?"); string interests = input.nextline(); 

the rest of code equals code have above.

edit: has (i mean, without storing line in of variables) because nextint() function don't read full line, next integer. so, when nextint() function read int, "cursor" of scanner in position after int.

for example, if put more 1 words (separated space) when trying reading int, in interests variable read rest of line nextint() couldn't read before. so, if have:

system.out.println("okay, " + name + ", " + gender + ". now, tell me, age?"); //here enter --> 18 prove int age = input.nextint(); system.out.println("great! we're done. 3 interests have?"); //here won't able put string interests = input.nextline(); 

now have stored:

age = 18; interests = "this prove"; 

but if put code this:

system.out.println("okay, " + name + ", " + gender + ". now, tell me, age?"); //here enter --> 18 prove int age = input.nextint(); input.nextline(); //now scanner go new line (because of nextline) without storing value system.out.println("great! we're done. 3 interests have?"); //now in new line , going able write. example --> reading this. string interests = input.nextline(); 

the values going have it's:

age = 18; interests = "i reading this."; 

so, in conclusion, if have nextint() , trying read single int read it, cursor stay @ final of line , won't able read next line. this, have read full line without storing input.nextline();.

i expect helpful you!


Comments

Popular posts from this blog

PHP DOM loadHTML() method unusual warning -

python - How to create jsonb index using GIN on SQLAlchemy? -

c# - TransactionScope not rolling back although no complete() is called -