java - Both next() and nextLine() not helping to store name with spacing -


i using scanner record user input string , print out. if user input single name such alan, works fine. if enter name spacing such alan smith, returns error saying inputmismatchexception.

i read around similar cases here , advised use nextline() instead of next(). made sense doesn't work me either. when use nextline(), skips step enter name , goes starting of loop asking me input choice again. please advice how can correct this. thank you.

import java.io.ioexception; import java.util.scanner;  public class scannertest {     static string name;     static scanner in = new scanner(system.in);     static int choice;      public static void main(string[] args) {               while(choice != 5){             system.out.print("\nenter choice :> ");             choice = in.nextint();              if(choice == 1){                 try{                     printname();                 }                 catch(ioexception e){                     system.out.println("io exception");                 }             }         }      }       private static void printname()throws ioexception{         system.out.print("\nenter name :> ");         name = in.next();         //name = in.nextline();          if (name != null){             system.out.println(name);         }     }   }   

try instead: add name = in.nextline(); after choice = in.nextint();.

then try replacing name = in.next(); name = in.nextline();

explanation: after scanner calls nextint() gets first value , leaves rest of string \n. consume rest of string nextline().

the second nextline() used string parameters.


Comments

Popular posts from this blog

android - Get AccessToken using signpost OAuth without opening a browser (Two legged Oauth) -

org.mockito.exceptions.misusing.InvalidUseOfMatchersException: mockito -

google shop client API returns 400 bad request error while adding an item -