-
ints and operators?
hello,
I had a quick, and hopefully easy question.
I have a variable with a string in it, like
private String bla = "5+3*4";
what i was wondering... i want to take all the ints and put them in an int array, and all the operators and put them in an operator array.
something like that
-
Here goes:
Code:
import java.util.*;
public class Expressionator {
ArrayList ops=new ArrayList();
ArrayList ints=new ArrayList();
// you might want to include brackets & parentheses here
String opers="+-*/";
public Expressionator(String s) {
StringTokenizer st=new StringTokenizer(s,opers,true);
while (st.hasMoreElements()) {
String whatzit=(String)st.nextElement();
if (opers.indexOf(whatzit)>=0) {
ops.add(whatzit);
} else {
ints.add(whatzit);
}
}
// if you insist on arrays then
int [] intArr=new int[ints.size()];
String [] operArr=new String [ops.size()];
for (int i=0;i<ints.size();i++) {
intArr[i]=Integer.parseInt((String)ints.get(i));
}
for (int i=0;i<ops.size();i++) {
operArr[i]=(String)ops.get(i);
}
System.out.println("The expression:"+s);
System.out.println("Integers:");
for (int i=0;i<intArr.length;i++) {
System.out.println(intArr[i]);
}
System.out.println("Operators:");
for (int i=0;i<operArr.length;i++) {
System.out.println(operArr[i]);
}
}
public static void main(String[] args) {
String s="";
for (int i=0;i<args.length;i++) {
s+=args[i];
}
Expressionator exp = new Expressionator(s);
}
}
eschew obfuscation
-
Hi all,
Nice job sjalle (as usal). You have been quicker than me 
May I mention yet :
StringTokenizer is a legacy class that is retained for compatibility reasons although its use is discouraged in new code. It is recommended that anyone seeking this functionality use the split method of String or the java.util.regex package instead.
Details are here
Best regards,
-
I know... I was told this as early as -96 I think, so its
really just a bad habit...
eschew obfuscation
-
Hi again sjalle,
Anyway, I obviously mentioned it for d00d, not for you
-
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Development Centers
-- Android Development Center
-- Cloud Development Project Center
-- HTML5 Development Center
-- Windows Mobile Development Center
|