Java splitting input

input, java, split, string

Solution

Try using the split() method on a string. It will return an array of Strings. For example

String s = 'walk 10';
String[] splitStrings = s.split(" ")

Now, to access 10, you can do this:

String distanceToWalk = splitStrings[1]

To convert it to an int, use the parseInt() method on Integer

Integer.parseInt(distanceToWalk);

See

- http://docs.oracle.com/javase/6/docs/api/java/lang/String.html#split%28java.lang.String%29

- http://docs.oracle.com/javase/6/docs/api/java/lang/Integer.html#parseInt%28java.lang.String%29

Problem

i'm trying to write a simple code for my project if user types walk 10 i need to use "walk" command in my walk(distance) method as distance = 10 i have something like that ``` while (!quit) { Scanner in = new Scanner(System.in); String input = in.nextLine(); // if (walk x is typed) { walk(x); } } ``` i'm using java.util.scanner and another problem is that my method walk(int x) uses int so i need to convert String input to int i searched the web for a while but couldnt find what i'm looking for (or i didnt understand it) so anyway i'd appreciate if you can help me thanks Thanks a lot for all the answers my initial problem is fixed but now i have another problem when i type just "walk" it gets array out of bounds exception of course because it tries to convert null to an int (not possible) i tried this and checked online ``` try { Integer.parseInt(splitStrings[1]); } catch(NumberFormatException e) { System.out.println("error: " + e); } ``` still no help (i'm not good with try/catches) so if user types walk without a distance i need to give an error message thanks a lot again ok i got it too just used a simple thing ``` if ("walk".equals(splitStrings[0])) { if (splitStrings.length == 2) { int distance = Integer.parseInt(splitStrings[1]); Robot.walk(distance); } if (splitStrings.length != 2) { System.out.println("Entry must be like walk 10"); } } ```

Original source