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