Reputation: 31
I was making a calculator in Kotlin and I'm having trouble solving an issue that I'm having with while()
.On this particular part of the code, I'm trying to find the first operator in the equation, but I need to exclude the ones that indicate whether a number is negative -
(or positive +
, optional), which need to be indicated between parentheses like so: (-5)
var charay = charArrayOf('+', '-', '*', '/')
var op = 0
var reference = 0
var bol = false
while( bol == false && op != -1){
println(op)
println(bol)
println(bol == false && op != -1)
op = input.indexOfAny(charay, reference)
if (!input.get(op - 1).equals('(')){
bol = true
}else{
reference = op + 1
}
println(op)
println(bol)
println(bol == false && op != -1)
}
To test a normal equation I entered the equation 4+4
and the console looks like this:
0
false
true
1
true
false
0
false
true
Exception in thread "main" java.lang.StringIndexOutOfBoundsException:
String index out of range: -2
at java.lang.String.charAt(String.java:658)
at CalculatorKt.CalculateValue(Calculator.kt:67)
at CalculatorKt.CalculateValue(Calculator.kt:108)
at CalculatorKt.main(Calculator.kt:119)
Like I suspected, for some reason, the variables reset at the end of the while()
, which is the reason why it never leaves said while()
. Can anyone tell me why?
Upvotes: 0
Views: 175
Reputation: 32066
Read the error. You're trying to read the character of a string at an index that doesn't exist with this statement:
input.get(op - 1)
You need to check what op
is first to make sure it is found. indexOfAny
returns -1
if not found in the string. Because we can't see what charay
is, we can't help you further.
Upvotes: 3