In: Computer Science
Unit 4: Discussion - Part 1
Question
Read the lecture for Chapter 4, and then answer the following:
Think of a brief example where you can use conditional
statements and write it in correct Java syntax. You may use
if-else-if statements or the switch statement. You may also use the
example you wrote in pseudo code for the discussion thread
2 during week 2 and convert it to Java, if you think it is
appropriate. Be mindful that we are not talking about
homework here. Do not post homework in this or any other discussion
thread. As always, show a screen capture of the
program running.
After writing your example, please explain if you think your
example could also be written in the other conditional statement
you did not chose. Explain why you think so, or why
not.
If you have any problem with the code feel free to comment
Program
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
//basic calculator app
Scanner sc = new
Scanner(System.in);
int num1, num2, choice;
System.out.print("Enter the first
number: ");
num1 = sc.nextInt();
System.out.print("Enter the second
number: ");
num2 = sc.nextInt();
System.out.println("1. Add\n2.
Subtract\n3. Multiply\n4. Divide");
System.out.print("Enter your
choice: ");
choice = sc.nextInt();
switchOperation(num1, num2,
choice);
ifelseOperation(num1, num2,
choice);
sc.close();
}
/*Switch case is more preferred as depending
upon the choice the calculation is performed
*and it will be faster than if/else staetemnet in this
case
*It also improves the clarity and readability of the
program*/
private static void switchOperation(int num1, int
num2, int choice) {
System.out.println("********The
Switch Statement********");
switch(choice) {
case 1:
System.out.println("The sum is "+(num1+num2));
break;
case 2:
System.out.println("The difference is "+(num1-num2));
break;
case 3:
System.out.println("The multiplication result is
"+(num1*num2));
break;
case 4:
System.out.println("The division result is "+(num1/num2));
break;
default:
System.out.println("Invalid choice!");
break;
}
}
/*The calculation can also be represented in
if/else statement but
* if else is used for checking boolean expressions
which makes it slower here */
private static void ifelseOperation(int num1, int
num2, int choice) {
System.out.println("********If Else
Statement********");
if(choice == 1)
System.out.println("The sum is "+(num1+num2));
else if(choice == 2)
System.out.println("The difference is "+(num1-num2));
else if(choice == 3)
System.out.println("The multiplication result is
"+(num1*num2));
else if(choice == 4)
System.out.println("The division result is "+(num1/num2));
else
System.out.println("Invalid choice!");
}
}
Output