java - Using a Scanner with a String Splitter -


i trying use string splitter display user input e.g. 1,2 coordinates display on console. don't errors when run code. however, attempt use splitter not seem work.

scanner scanner = new scanner(system.in); system.out.println("enter row , column number @ shoot (e.g., 2,3): "); string[] coordinates = scanner.nextline().split(","); if (coordinates.length != 2) {     system.out.println("please enter coordinates in correct format.");     system.out.println("\nplayer 1 please take turn:");     continue; }  system.out.println("\nenter mine location:");  system.out.println("\nplease enter x position mine:"); system.in.read(byt); str = new string(byt); row = integer.parseint(str.trim());   system.out.println("\nplease enter y position mine:"); system.in.read(byt); str = new string(byt); col = integer.parseint(str.trim()); 

your use of system.in.read(...) dangerous code , not doing think it's doing:

system.in.read(byt); // ***** str = new string(byt); row = integer.parseint(str.trim());  

instead use scanner, something have, , either call getnextint() on scanner, or line , parse it.

also, never use strings held in coordinates array -- why strings if ignoring them?


you ask about:

scanner scanner = new scanner(system.in);  system.out.println("enter row , column number @ shoot (e.g., 2,3): ");  str = scanner.nextint().split(",");  

but see compiler won't allow since you're trying call method on int primitive scanner.nextint() returns.

my recommendation use scanner#nextint() replacement misuse of system.in.read(...). if instead want user enter 2 numbers on 1 line, separated comma, you're best bet use string.split(","), although, think might better use string.split("\\s*,\\s*") rid of white space such spaces hanging about. way split should work 1,1 1, 2 , 1 , 2, , can parse items held in array via integer.parseint(...).


Comments

Popular posts from this blog

dns - How To Use Custom Nameserver On Free Cloudflare? -

python - Pygame screen.blit not working -

c# - Web API response xml language -