I am making an English Calculator and that is, for example, when the String is "1 plus 2", I split the words into 3 parts using split. The split elements are 1 & plus & 2, and the last job is just to add the numbers. It worked well when I used Switch, but I tried to use For method for practice and it prints out 0.0 for "1 plus 2" sentence... I think there is a problem in arraylist but have no one to ask.. Can I please get an idea of how to fix it?
Also, I`d like to know, for example, saying that the String is, "4 divided by 2". The elements are four, but the question is, how can I split the two words, "divided by" at same time? Thanks!
class Calculator {
public static double calculate(String s) {
List<String> list = new ArrayList<>(Arrays.asList(s.split(" ")));
//System.out.println(list.size());
double value1, value2;
double result = 0.0;
String operator;
int i = 0;
for(i = 0; i < list.size(); i++)
{
if(list.size() == 3)
{
operator = list.get(1);
value1 = Double.parseDouble(list.get(0));
value2 = Double.parseDouble(list.get(2));
if(operator == "plus")
{
result = value1 + value2;
} else if(operator == "minus")
{
result = value1 - value2;
} else if(operator == "times")
{
result = value1 * value2;
} else if(operator == "mod")
{
result = value1 % value2;
}
}
}
return result;
}
}
class MyPractice
{
public static void main(String[] args)
{
Calculator cal = new Calculator();
System.out.println(cal.calculate("1 plus 2"));
}
}