Using a conditional expression, write a statement that increments numUsers if up
ID: 3820385 • Letter: U
Question
Using a conditional expression, write a statement that increments numUsers if updateDirection is 1, otherwise decrements numUsers. Ex: if numUsers is 8 and updateDirection is 1, numUsers becomes 9; if updateDirection is 0, numUsers becomes 7. import java.util.Scanner; public class UpdateNumberOfUsers {4 public static void main (String [] args) {int numUsers = 0; int updateDirection = 0; numUsers = 8; updateDirection = 1; /* Your solution goes here */ System.out.println("New value is: " + numUsers); return;}}Explanation / Answer
Source Code:
public class UpdateNumberOfUsers {
public static void main(String[] args) {
int numUsers = 0;
int updateDirection = 0;
numUsers = 8;
updateDirection = 1;
numUsers = (updateDirection == 1) ? numUsers + 1 : numUsers - 1;
System.out.println("New value is: " + numUsers);
return;
}
}
Description:
Here, you are required to write a conditional expression and as hint suggests, it starts with numUsers = ...
So, you are supposed to use the conditional operators here.
Then, the bold and underlined line is the line you need to insert in the code.
If updateDirection is 1 then you should increase numUsers by 1 otherwise decrease it by 1. So, this can be written in if-else statments as :
if(updateDirection == 1)
numUsers = numUsers + 1;
else
numUsers = numUsers - 1;
So, to write this in the conditional expression, the if condition goes inside the ( ) . If it is true, perform the action written after ? and if it false, perform the operation written after :
So, the required line can be written as : numUsers = (updateDirection == 1) ? numUsers + 1 : numUsers - 1;
If you execute the program after writing this line, you will get " New value is: 9 " in the output.
Please comment if there is any query. Thank you. :)
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.