(Android Studio) Odd or even

Asked

Viewed 1,207 times

0

I’m a beginner in Android Studio and I need to make an app that gets a number in Edittext and then tell me if it is even or odd, follow my current code : I don’t know what and where to put to when press the button (I’ve already done) have this result... Help

public class exercicio1 extends AppCompatActivity {

TextView tInforme;
EditText tValor;
Button btDescobrir;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_exercicio1);

    tInforme = (TextView) findViewById(R.id.tInforme);
    tValor = (EditText) findViewById(R.id.tValor);
    btDescobrir = (Button) findViewById(R.id.btDescobrir);}


        public void setbtDescobrir(View v) {
            String guessStr = tValor.getText().toString();
            int theGuess = Integer.parseInt(guessStr);

        }}

1 answer

0


Use the the operation % it returns you the rest of a division. In case divided by 2 %2and if the result is 0 it means that it is even, if it is not odd

edited:

String guessStr = tValor.getText().toString();
   int theGuess = Integer.parseInt(guessStr);
   int valor = theGuess%2;
   if(valor == 0){
      //imprima é par
   }
   else if(valor == 1){
    // imprima é impar
   }
  • Okay, but where exactly do I put this and how ? I tried to do this and always gives error, since I pull "btValor" (which is the id of Edittext), if and it does not accept the %operator. Obg

  • public void setbtDescobrir(View v) { String guessStr = tvalor.gettext(). toString(); int theguess = Integer.parseint(guessStr); Return theguess%2; }}

  • you must take the value that is in int, in the case theguess and check which is the rest of the division, you can also make an int value = theguess%2; if value is equal to 0 is even, if it is equal to 1 is odd

  • I don’t remember very well how the structure of an android works but surely the logic I gave you is right, if( value == 0) { // print is even}Else{///print is odd}

  • Okay, obg, I’ll try here

  • edited the answer, I think it will help you more

  • Got it here, mto xD obg

Show 2 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.