java – How to convert string to int to fit in a if statement-ThrowExceptions

Exception or error:

Since adding image to the sqlite DB is a bust I might as well just add some other things on my quiz app.

I have this quiz app where I want to have an if else statement when the user gets 4 below it will have a sad sound effect and 5 above it will play a happy sound effect.

I know how to do that (I hope so) but the thing I don’t know is how do I convert a string back to int in order for me to accept it in a if statement.

  1. CoinValue here is first declared as an int
    int coinValue = 0;
  1. However it is then turned into a string in a later code
 coinText.setText(String.valueOf(coinValue));

*I already tried some codes earlier but it just gives off an error.

  1. I then have an intent to get the score then transfer it to the results page
intent.putExtra("score", coinValue);

Once it is transferred to the results page it’s already a string right? It all works I just want to make the coinValue an int so when It goes to the results I can code it to the if statement.

How to solve:

After looking at your question the answer for how to convert a String to int has already been mentioned as a comment by @Elliot using Integer.parseInt(coinText.getText());, but there’s something else I would like to mention.

you said

  1. However it is then turned into a string in a later code

Well not really, the coinValue is still an integer and you just set it as a String into the TextView coinText. Meaning it remains as an int with no changes in its original value and only its value is used as a String to set in the textView, that’s all.

So now when you use

intent.putExtra("score", coinValue);

This is adding an integer value as an extra to the intent you are passing to the results page. which you will have to retrieve using

getIntent().getIntExtra("score", 0);    //where 0 is the default int value. you may change it as you require

So basically you coinValue remains an int and it is that integer value you are passing to results where you retrieve it and proceed without a need for conversion from String to int.

Hope this was of some help to you..

Leave a Reply

Your email address will not be published. Required fields are marked *