Recap - If Else
Part of the Fundamentals section of Coddy's Java journey — lesson 31 of 73.
Challenge
BeginnerYou are given a code which gets as input two numbers n1 and n2 and a single char string op.
Note: we will learn in next lessons how to get input from the user, currently just don't touch the three first lines.
The possible values for op are +, -, / and *
Your task is to set the variable result based on the conditions:
- if
opis+, setresultwithn1 + n2. - if
opis-, setresultwithn1 - n2. - if
opis/, setresultwithn1 / n2. - if
opis*, setresultwithn1 * n2.
Important: In Java, strings cannot be compared with ==. To compare a string, use the .equals() method instead. For example, to check if op is +, write: op.equals("+")
Try it yourself
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in); // Don't change this line
int n1 = scanner.nextInt(); // Don't change this line
int n2 = scanner.nextInt(); // Don't change this line
scanner.nextLine(); // Don't change this line
String op = scanner.nextLine(); // Don't change this line
// Write your code below
double result = 0;
System.out.println(result);
}
}All lessons in Fundamentals
4Operators Part 1
Arithmetic OperatorsModulo OperatorIncrement/DecrementPost Increment/DecrementArithmetic ShortcutsComparison OperatorsString Comparison5Operators Part 2
Logical Operators Part 1Logical Operators Part 2Recap - Simple LogicLogical Operators Part 3Logical Operators Part 43Variables Part 2
ConstantsNaming ConventionsRecap - Initialize VariablesType Casting Part 1Type Casting Part 26Decision Making
If StatementIf - ElseSwitch StatementTernary OperatorRecap - If ElseNested If - Else