Question: Consider the following Java method, which is written incorrectly: Under what cases will the method print the correct answer, and when will it print an

Consider the following Java method, which is written incorrectly:

// This method should return how many of its three // arguments are odd numbers. public static void printNumodd (int ni, int n2, int n3) { int count = 0; if (nl % 2 != 0) { count++; } else if (n2 % 2 != 0) { count++; } else

Under what cases will the method print the correct answer, and when will it print an incorrect answer? What should be changed to fix the code? Can you think of a way to write the code correctly without any if/else statements?

// This method should return how many of its three // arguments are odd numbers. public static void printNumodd (int ni, int n2, int n3) { int count = 0; if (nl % 2 != 0) { count++; } else if (n2 % 2 != 0) { count++; } else if (n3 % 2 != 0) { count++; System.out.println (count + " of the 3 numbers are odd.");

Step by Step Solution

3.33 Rating (171 Votes )

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock

The code fails when more than one number is odd because it uses else if rather than if The t... View full answer

blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Building Java Programs A Back to Basics Approach Questions!