简体   繁体   中英

Java stringtokenizer assignment trouble

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?

  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.

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

您可以这样使用while(st.hasMoreTokens()){/ ...}

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM