Reputation: 21
I am supposed to evaluate a string by splitting the string in tokens using the StringTokenizer class. After that I am supposed to convert these tokens to int values, using "Integer.parseInt".
What I don't get is how I am supposed to work with the tokens after splitting them.
public class Tester {
public static void main(String[] args) {
String i = ("2+5");
StringTokenizer st = new StringTokenizer(i, "+-", true);
while (st.hasMoreTokens()) {
System.out.println(st.nextToken());
}
int x = Integer.parseInt();
//what exactly do I have to type in here, do convert the token(s) to an int value?
}
}
So if I understand this right I now have three tokens. That would be: "2", "+" and "5".
How exactly do I convert these tokens to int values? Do I have to convert each of them seperatly?
Any help is appreciated.
Upvotes: 0
Views: 429
Reputation: 171
To have a possibility to make some calculations with the Integers extracted from the String, you have to put them into an ArrayList. And you have to use try/catch operation to avoid a NumberFormatException. Further you can take the values directly from the ArrayList and do with them what you'd like. For example:
public static void main(String[] args) {
ArrayList <Integer> myArray = new ArrayList <>();
String i = ("2+5");
StringTokenizer st = new StringTokenizer(i, "+-/*=", true);
while (st.hasMoreTokens()) {
try {
Integer stg = Integer.parseInt(st.nextToken(i));
myArray.add(stg);
}
catch (NumberFormatException nfe) {};
}
System.out.println("This is an array of Integers: " + myArray);
for (int a : myArray) {
int x = a;
System.out.println("This is an Integer: " + x);
}
int b = myArray.get(0);
int c = myArray.get(1);
System.out.println("This is b: " + b);
System.out.println("This is c: " + c);
System.out.println("This is a sum of b + c: " + (b + c));
}
As a result you'll get:
This is an array of Integers: [2, 5]
This is an Integer: 2
This is an Integer: 5
This is b: 2
This is c: 5
This is a sum of b + c: 7
Upvotes: 1
Reputation: 521
Maybe you can use this:
String i = ("2+5");
StringTokenizer st = new StringTokenizer(i, "+-", true);
while (st.hasMoreTokens()) {
String tok=st.nextToken();
System.out.println(tok);
//what exactly do I have to type in here, do convert the token(s) to an int value?
if ("+-".contains(tok)) {
//tok is an operand
}
else {
int x = Integer.parseInt(tok);
}
}
Upvotes: 1