Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Android

if / else statements

Hello, I try to do if and else statements in android and I don't get what I need. so, I very happy if someone can help me about it. so, I have six Buttons in my project and each of button should give me data when the user is push the Button that he choose, my code for evrey Button is Like this: mButtonSport.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { getNews(0); } }); and this is the name of data of every Button:

  1. String Sport = "some data", 2. String Business = "some data", 3. String Music = "some data", 4. String Business = "some data", 5.String Politicis = "some data", 6. String Health = "some data", so My code is this: and I dont get the correct data to each Button, someone can please can help me about it ?

    String myData;
    if (dataType == 0) {
        myData= sport;
    } else {
        myData = business;
    }
    if (dataType == 1) {
        myData = business;
    } else {
        myData = music;
    }
    if (dataType == 2) {
        myData = music;
    } else {
        myData = politics;
    }
    if (dataType == 3) {
        myData = politics;
    } else {
        myData = health;
    }
    if (dataType == 4) {
        myData= health;
    } else {
        myData =technology;
    }
    if (dataType == 5) {
        myData = technology;
    } else {
        myData = business;
    }
    

Thanks for Help :)

1 Answer

Seth Kroger
Seth Kroger
56,413 Points

The code will run through each of the if/else statements. Since you're assigning myData on every branch, only the final if/else statement is relavant, because myData will be set to either technology or business regardless of whatever happens before. Given that you probably want it set differently for each data type it would be better to use an if/else-if chain, or for that matter a switch statement.

Thanks you very much about your answer it's very help me :).. now I understand what to do , I use in "else if" - statements and now it work to me like I need :), have a nice day Seth Kroger !