if Statement Examples

Contact Us or call 1-877-932-8228
if Statement Examples

if Statement Examples

Absolute Value

If we needed the absolute value of a number (a number that would always be positive):

Code Sample:

Java-Control/Demos/If1.java
public class If1 {
  public static void main(String[] args) {
    int a = 5;
    System.out.println("original number is: " + a);
    if ( a < 0 ) { a = -a; }
    System.out.println("absolute value is: " + a);
    a = -10;
    System.out.println("original number is: " + a);
    if ( a < 0 ) { a = -a; }
    System.out.println("absolute value is: " + a);
  }
}

Random Selection

Task: write a brief program which generates a random number between 0 and 1. Print out that the value is in the low, middle, or high third of that range (Math.random() will produce a double value from 0.0 up to but not including 1.0).

  • Although it is a bit inefficient, just do three separate tests: (note that Math.random() will produce a number greater than or equal to 0.0 and less than 1.0).

Code Sample:

Java-Control/Demos/If2.java
public class If2 {
  public static void main(String[] args) {
    double d = Math.random();
    System.out.print("The number " + d);
    if (d < 1.0/3.0) 
      System.out.println(" is low");
    if (d >= 1.0/3.0 && d < 2.0/3.0) 
      System.out.println(" is middle");
    if (d >= 2.0/3.0) 
      System.out.println(" is high");
  }
}
Next