|
|
Re: Array problem
|
Posted: Feb 9, 2006 11:08 PM
|
|
This sounds much like homework to mee, but I'm in a good mood, so here you go:
It's very easy, but I had to make one change. a number follows another number, the second number will be added.
enum Operations {ADD, SUBTRACT, DIVIDE, MULTIPLY};
public static void operation1 (String[] dbcolumn1){
double currentValue = 0;
Operations operation = ADD;
for (String s : dbcolumn1) { //this works only for Java 1.5, use tthe following lines for earlier Java versione
// for (int i = 0; i < dbcolumn1.length; i++) {
// String s = dbcolumn1[i];
if ("/".equals(s))
operation = Operations.DIVIDE;
else if ("*".equals(s))
operation = Operations.MULTIPLY;
else if ("+".equals(s))
operation = Operations.ADD;
else if ("-".equals(s))
operation = Operations.SUBTRACT;
else { //Number
double val = 0;
try {
val = Double.parseDouble(s);
} catch (NubmerFormatException e) {
System.out.println ("Parse error. Assuming 0");
}
if (operation == Operations.ADD)
currentValue = currentValue + val;
else if (operation == Operations.SUBTRACT)
currentValue = currentValue - val;
else if (operation == Operations.MULTIPLY)
currentValue = currentValue * val;
else // divide
currentValue = currentValue / val; //this can result in an Exception if val == 0
operation = Operations.ADD; //this is the change I mentioned above.
}
}
System.out.println (currentValue);
}
Sorry if there are some errors in the text, but I didn't write this in a IDE and didn't compile it.
|
|