ayeshariaz_ash
ayeshariaz_ash

Reputation: 3

Checking temperature conditions

How could I set appropriate temperature within these three conditions at least at 98°C, 99°C, 1°C & 2°C etc?

package boiling.freezing;

import java.util.Scanner;

public class BoilingFreezing {

    public static void main(String[] args) {
        System.out.println("Give the temperature : ");
        Scanner sc = new Scanner(System.in);
        int temp = sc.nextInt();
        if (temp >= 100){
            System.out.println("The water is boiling!");
        }
        else if (temp <= 0){
            System.out.println("The water is freezing!");
        }
        else{
            System.out.println("The water is at normal_state!");
        }
    } 
}

Upvotes: 0

Views: 1198

Answers (2)

sandesh dahake
sandesh dahake

Reputation: 1026

Based on LppEdd's answer if you are using Java 8+ you can make use of java predicate

java.util.function.Predicate was introduced that behaves as an assignment target in lambda expressions and functional interfaces. The functional method of Predicate is test(Object) .

Upvotes: 0

LppEdd
LppEdd

Reputation: 21134

I'm going to offer you a pattern, not a simple if-elseif-else block.

You might want to have an interface Temperature

interface Temperature {
   /** Returns true if the temperature matches the criteria. */
   boolean within(final int temperature);

   /** Returns an appropriate, descriptive, message. */
   String message();
}

You can then implement this interface to meet your multiple criteria

class BoilingTemperature implements Temperature {
   public boolean within(final int temperature) {
      return temperature > 99;
   }

   public String message() {
      return "Water boiling";
   }
}

class FreezingTemperature implements Temperature {
   public boolean within(final int temperature) {
      return temperature < 1; // Should be 3 degree! But anyway.
   }

   public String message() {
      return "Water freezing";
   }
}

You can use this pattern to write custom temperature handlers

class YourCustomTemperature implements Temperature {
   public boolean within(final int temperature) {
      return temperature > 6 && temperature < 40;
   }

   public String message() {
      return "Your custom message";
   }
}

You need to maintain a list of those concrete implementations and loop them to check which matches.

final List<Temperature> temperatures = new ArrayList<>(6);
temperatures.add(new BoilingTemperature());
temperatures.add(new FreezingTemperature());
temperatures.add(new YourCustomTemperature());
...

And then

public static void main(String[] args) {
    System.out.println("Give the temperature : ");
    final Scanner sc = new Scanner(System.in);
    int temp = sc.nextInt();

    for (final Temperature t : temperatures) {
       if (t.within(temp)) {
          System.out.println(t.message());
       } 
    }
}

Upvotes: 1

Related Questions