Profit or Loss in Java

Determine profit or loss based on cost price and selling price.

BeginnerModule 2: Conditional ProgramsExample 12 of 20
profit-or-loss.java
1import java.util.Scanner;
2
3public class Main {
4 public static void main(String[] args) {
5 Scanner sc = new Scanner(System.in);
6
7 System.out.print("Enter cost price: ");
8 double cp = sc.nextDouble();
9 System.out.print("Enter selling price: ");
10 double sp = sc.nextDouble();
11
12 if (sp > cp) {
13 System.out.println("Profit = " + (sp - cp));
14 } else if (sp < cp) {
15 System.out.println("Loss = " + (cp - sp));
16 } else {
17 System.out.println("No profit, no loss");
18 }
19
20 sc.close();
21 }
22}

Output

Enter cost price: 100
Enter selling price: 120
Profit = 20.0

What's going on

We compare selling price to cost price and compute either profit or loss accordingly.