3

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");
                }
            }
3
  • is there space between them ? Commented May 3, 2012 at 2:22
  • yes user types walk 10 or walk 25 Commented May 3, 2012 at 2:23
  • You can Integer.parseInt to get the int value that you need after using split to get all tokens in the input line Commented May 3, 2012 at 2:23

6 Answers 6

7

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

  1. http://docs.oracle.com/javase/6/docs/api/java/lang/String.html#split%28java.lang.String%29
  2. http://docs.oracle.com/javase/6/docs/api/java/lang/Integer.html#parseInt%28java.lang.String%29
Sign up to request clarification or add additional context in comments.

1 Comment

thanks a lot. that was exactly what i was looking for both splitting the input in 2 from white space and converting 10 to integer
7

You can split on the space, in which case the number would be the second element (index 1) of the resulting array e.g.

Edit following comment from Adam Liss

Integer x = Integer.parseInt(input.split(" ")[1])

4 Comments

+1 for a neat solution, though given that this is user input you would also want to strip out excess spaces first (otherwise your number will be in the wrong place in the array).
Wait, what??? You can't cast a String to an Integer! Shame on all you upvoters.
@AdamLiss You are absolutely correct, modified the answer accordingly.
@Strawberry +1 for updating. Also for the audacity to post an answer that wasn't even valid Java ... and still managing to get 3 upvotes!
1

You can use the Integer.parseInt() method:

int distance = Integer.parseInt(input);

Comments

0

Try:

String s = 1;
int i = Integer.parseInt(s); // returns 1

Comments

0

Assuming you strip out the integer portion from the string, eg leaving an input of

"walk 10" with "10", just use something like

// say you've parsed the "number" portion into a variable "inputString"
int x;
x= Integer.parseInt(inputString);

Comments

0

You can use this:

// For read the input
InputStreamReader streamReader = new InputStreamReader(System.in);
BufferedReader reader = new BufferedReader(streamReader);
String input = reader.readLine();

If you prefer use Scanner, then

Scanner sc = new Scanner(System.in);
String input = sc.nextLine();

Then:

StringTokenizer st = new StringTokenizer(input);
if (st.countTokens == 2) { // Only for two tokens "walk 100", "return 10"
    String method = st.nextToken();
    if (method.equals("walk") { // if you have more methods like "walk"
        int distance = Integer.parseInt(st.nextToken());
        walk(distance); // walk
    }
}

If you want to read more lines

for(String input; sc.hasNextLine();) {
    input = sc.nextLine();

    // do something

}

Or

for(String input; (input = reader.readLine()) != null;) {

    // do something

}

2 Comments

how can i use tokenizer with java.util.scanner?
I added for StringTokenizer and Scanner.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.