a2krocks
a2krocks

Reputation: 945

How to check that string is not equal to a string then it will work otherwise no? in kotlin

I have a problem to share with you guys a I am trying to check if a string is not equal to nothing and it should be "." value a string if it pass it will do certain line code if not it simply print something but the problem is when i try to put value "." it crashes. So is there any way to fix this?

Here is my kotlin main activity file :

calculate.setOnClickListener {

        if(((distance.text.toString().length >0) &&
                (initalVelocity.text.toString().length>0) &&
                (time.text.toString().length > 0)
                ) && (!((distance.equals(".")) &&
                (initalVelocity.equals(".")) &&
                (time.equals("."))))) {
            val s = distance.text.toString().toDouble()
            val u = initalVelocity.text.toString().toDouble()
            val t = time.text.toString().toDouble()
            val a = (((2* s))-(2*(u*t)))/(t*t)
            answer.setText("answer $a m/(s)^2")
        } else {
            toast("Are u nuts !!!!")
        }

LOG:

 FATAL EXCEPTION: main
Process: com.a3.apurv.physicscalculator, PID: 16094
java.lang.NumberFormatException: For input string: "."
    at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:2043)
    at sun.misc.FloatingDecimal.parseDouble(FloatingDecimal.java:110)
    at java.lang.Double.parseDouble(Double.java:539)
    at com.a3.apurv.physicscalculator.AccelerationIVActivity$onCreate$2.onClick(AccelerationIVActivity.kt:31)
    at android.view.View.performClick(View.java:6294)
    at android.view.View$PerformClick.run(View.java:24770)
    at android.os.Handler.handleCallback(Handler.java:790)
    at android.os.Handler.dispatchMessage(Handler.java:99)
    at android.os.Looper.loop(Looper.java:164)
    at android.app.ActivityThread.main(ActivityThread.java:6494)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)

Upvotes: 0

Views: 5312

Answers (2)

BakaWaii
BakaWaii

Reputation: 6992

The problem is in this part of your code:

!((distance.equals(".")) && (initalVelocity.equals(".")) && (time.equals(".")))

It will be true if any of the string doesn't equal to ".". Also, you are comparing the EditText instance instead of the content of it. The condition of your if case should be:

if(distance.text.toString().length > 0 && 
        initalVelocity.text.toString().length > 0 &&
        time.text.toString().length > 0 &&
        !(distance.text.toString().equals(".") || initalVelocity.text.toString().equals(".") || time.text.toString().equals(".")))

Here is an alternative way to approach the same result:

val s = try { distance.text.toString().toDouble() } catch(e: Exception) { null }
val u = try { initalVelocity.text.toString().toDouble() } catch(e: Exception) { null }
val t = try { time.text.toString().toDouble() } catch(e: Exception) { null }
if (s != null && u != null && t != null) {
    val a = (((2* s))-(2*(u*t)))/(t*t)
    answer.setText("answer $a m/(s)^2")
} else {
    toast("Are u nuts !!!!")
}

I use try-catch instead of if-else because calling toDouble of "" and "." will both throw NumberFormatException.

Upvotes: 1

toniedzwiedz
toniedzwiedz

Reputation: 18553

Your code is failing because you're trying to convert the string "." to a number. toDouble (from kotlin-stdlib) will throw a NumberFormatException if the string you're trying to convert is not a valid representation of a number.

The documentation does not specify what the format is so let's dig a little deeper. Judging by the source code, this uses Double#parseDouble(String) internally. This, in turn, uses Double#valueOf(String). If you're treating user input as Double values, have a look at the Javadoc and see what the method does and when. "." might not be the only input you allow that may cause the exception to be thrown. Depending on how complex the cases you need to support in your project are, you may also need to get acquainted with NumberFormat

That said, you need to change your conditional logic to make sure "." (or other non-numeric strings) don't get converted to Double or, alternatively, catch the NumberFormatException after it's thrown and handle it in a user-friendly way.

Upvotes: 1

Related Questions