Question 1 Rewrite the code snippets below as specified in each part. Where nece
ID: 3715115 • Letter: Q
Question
Question 1
Rewrite the code snippets below as specified in each part. Where necessary, you may assume that all involved variables and/or methods are already properly defined and/or initialized.
Submit your answers directly in the answer box, making sure to mark clearly the answers to the three parts.
Part A (5 pts):
The following code snippet assigns a value to the int variable price, depending on the String object item:
Transform the above logic into a single equivalent assignment statement, using the conditional operator ?:.
Part B (10 pts):
The following code snippet calls a different method according to the value of the int variable choice:
Transform the above logic into an equivalent switch statement.
Part C (10 pts):
In the following code snippet, total is an int variable:
Transform the above into an equivalent for loop.
For the toolbar, press ALT+F10 (PC) or ALT+FN+F10 (Mac).Explanation / Answer
Part A
Given code is converted to
price = (!item.equals("car")) ? 190 : 12000;
The syntax is variable = condition ? <true part> : <false part>;
Part B
Code converted to Switch statement is as follows
switch(choice) {
case 1:
retry();
break;
case 2:
case 3:
proceed();
break;
default:
goBack();
}
Part C
Equivalent code in for loop is
for(int num = total; num >= 0; num = num -2) {
System.out.println(num);
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.