0

So I'm having trouble with an assignment where I need to return the first or second token of a string, based on the given argument, using the stringtokenizer constructs and methods. EX: "3+5", 2. the return on this should be 5. Now what I have so far is:

    StringTokenizer st = new StringTokenizer (input, "+-*/%");
      if (st.hasMoreTokens());
    return st.nextToken();

this returns the first token of the string, but im unsure of how to return the second token. any advice?

4 Answers 4

2
  if (st.hasMoreTokens());

Should be

  if (st.hasMoreTokens())

There is an extra ;, With that extra ; your code like writing,

if(..)
{

}

 return st.nextToken();

Edit :

Moreover you need to form a string and then return. Not return st.nextToken(); that terminates your loop and returns the first value.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, that did help me a bit. But im still uncertain about returning the second token based on the given argument
1

This will help you. For this program to work, we need two parameters - Input String, position of the wanted token. In the below program, I have hard coded the position of the wanted token as '3'. so, the output would be '10', since it is the third token of the input string - 3+5*10*12+11

public static void main(String[] args) {
    //input string 
    String input = "3+5*10*12+11";
    // number of token we need
    int wantedToken = 3;
    // token number defaults to '1' and keeps track of the token position
    int i = 1;
    StringTokenizer st = new StringTokenizer(input, "+-*/%");
    while (st.hasMoreTokens()) {
        //when i equals wanted token, print it
        if (i == wantedToken) {
            System.out.println("wanted token : " + st.nextToken());
            break;
        } 
        else {
            //move to next token
            st.nextToken();
            //increment the token position
            i++;
        }
    }

}

Output:

run:
wanted token : 10
BUILD SUCCESSFUL (total time: 0 seconds)

Update: Converted the above code - a Seperate Method. The below code takes input string and wanted token from user

public class WantedTokenTest {

    public static void main(String[] args) {
          //input string 
        String input = null;
        // number of token we need
        int wantedToken = 1;
        Scanner scr = new Scanner(System.in);
        System.out.println("Please enter the input string : ");
       input =  scr.nextLine();
        System.out.println("Please enter the wanted token : ");
       wantedToken =  scr.nextInt();

        System.out.println(getWantedToken(input, wantedToken));

    }


    private static String getWantedToken(String input,int wantedToken){
           // token number defaults from '1' and keeps track of the token position
        int i = 1;
        StringTokenizer st = new StringTokenizer(input, "+-*/%");
        while (st.hasMoreTokens()) {
            //when i equals wanted token, print it
            if (i == wantedToken) {
               return st.nextToken();

            } 
            else {
                //move to next token
                st.nextToken();
                //increment the token position
                i++;
            }
        }
        return null;
    }
}

Hope, it clarifies how to do it

2 Comments

This was vey helpful, thank you! I have one more question though, I did not make this very clear but how would you return any token within the equation without hardcoding it in? As if the user input the token they want.
Just get the wanted token from user using Scanner API and make this code as a seperate method with two parameters. i.e. input string, position of the wanted token
0

you can use like this while(st.hasMoreTokens()) { /... }

Comments

0

If you want to parse math expression with Tokenizer you should do it dinamically. You could take a look at answer1 and answer2.

But if you just want to get the second token try this code:

public static List<String> getTokens(String input) {
    List<String> tokens = new ArrayList<String>();
    StringTokenizer st = new StringTokenizer(input, "+-*/%");
    while (st.hasMoreTokens()) {
        tokens.add(st.nextToken());
    }
    return tokens;
}
public static void main(String[] args) {
    List tokens = getTokens("3+5");
    System.out.println(tokens.get(0));
    System.out.println(tokens.get(1));//the second token
}

OR

public static String[] getTokens (String input) {
    return input.split("[-\\+\\*\\\\]");
}
public static void main(String[] args) {
    String[] tokens = getTokens("3+5");
    System.out.println(tokens[0]);
    System.out.println(tokens[1]);//the second token
}

Comments

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.