283,926 views
43 votes
43 votes
Consider the following code segments, which are each intended to convert grades from a 100-point scale to a 4.0-point scale and print the result. A grade of 90 or above should yield a 4.0, a grade of 80 to 89 should yield a 3.0, a grade of 70 to 79 should yield a 2.0, and any grade lower than 70 should yield a 0.0.

Assume that grade is an int variable that has been properly declared and initialized.
Code Segment I
double points = 0.0;
if (grade > 89)
{points += 4.0;}
else if (grade > 79)
{points += 3.0;}
else if (grade > 69)
{points += 2.0;}
else
{points += 0.0;}
System.out.println(points);
Code Segment II
double points = 0.0;
if (grade > 89)
{points += 4.0;}
if (grade > 79)
{grade += 3.0;}
if (grade > 69)
{points += 2.0;}
if (grade < 70)
{points += 0.0;}
System.out.println(points);
Which of the following statements correctly compares the values printed by the two methods?

User Mickthompson
by
2.8k points

1 Answer

6 votes
6 votes

Answer:

The values printed by the two code segments will be the same.

Both code segments use a series of if statements to assign a value to the variable "points" based on the value of the variable "grade". In Code Segment I, the if statements are structured such that only the first one that evaluates to true will execute, and the value of "points" will be set accordingly. In Code Segment II, all of the if statements will execute, and the value of "points" will be the sum of all of the values that were added.

For example, if "grade" is 85, both code segments will execute the second if statement and add 3.0 to "points". Therefore, both code segments will print the same value in this case.

If you wanted to compare the values printed by the two code segments, you could test them using a variety of different values for "grade" and see if the output is consistent.

Step-by-step explanation:

User Vikas Khunteta
by
3.4k points