rwpk9 :
So, I'm trying to make a calculator that respects multiplications and divisions order, I'm typing a String, for example "6+43/2-5*12" and my program should find the first division or multiplication position.
I can find the first multiplication on the String like:
int first_mult = string.indexOf('*');
And the first division the String like:
int first_div = string.indexOf('/');
That works, but I want to find the first multiplication or division at same time, I've tryed:
int first_oper = string.indexOf('*'||'/');
But that don't works. Is there any way to do it?
Andy Turner :
One way is to use an IntStream
:
int first_oper = IntStream.range(0, string.length())
.filter(i -> string.charAt(i) == '*' || string.charAt(i) == '/')
.findFirst()
.orElse(-1);
Or, of course, use a loop:
for (int i = 0; i < string.length(); ++i) {
switch (string.charAt(i)) {
case '*': case '/': return i;
}
}
return -1;