Westonci.ca offers fast, accurate answers to your questions. Join our community and get the insights you need now. Get immediate answers to your questions from a wide network of experienced professionals on our Q&A platform. Explore comprehensive solutions to your questions from a wide range of professionals on our user-friendly platform.

Can anyone help me figure out why my if statements are not executing properly? When the program executes with 7 as the value for num it should be executing the first line, but instead it goes to the third and displays, " a single digit."

public static String numberInfo(int num){
//TODO student
String numInfo;

if (num == 7) {
numInfo = "lucky sevens!";
}
if (num == 42) {
numInfo = "the answer to life the universe and everything.";
}
if (num < 10) {
numInfo = "a single digit.";
}
else {
numInfo = "a positive number.";
}
return numInfo;
}


Sagot :

tonb

Answer:

For the value of 7 of num, there are actually two if statements that are true and their contained code is executed.

So your line numInfo = "lucky sevens!"; is executed for sure, but then numInfo gets overwritten with by numInfo = "a single digit.";

To fix it, you have to decide how you want the program to behave, since technically, both numInfo's are equally correct.

- if you want to execute at most one if condition, chain them together like if (...) { ... } else if(...) { ... } etc.

- if you want to return multiple numInfo's, turn it into a collection where you add strings

Thank you for your visit. We're dedicated to helping you find the information you need, whenever you need it. Thanks for using our platform. We aim to provide accurate and up-to-date answers to all your queries. Come back soon. Westonci.ca is your trusted source for answers. Visit us again to find more information on diverse topics.