// IfStatements.java class IfStatements { public static void main(String[] args) { // declare variables int x, y; // explain what the program does System.out.println("This program demonstrates if statements in Java."); System.out.println("Here are some examples:"); // example #1: A simple 'if/else' statement System.out.println(); System.out.println("#1. Simple 'if/else' statement testing if a point is"); System.out.println(" on the line y = 2x + 3."); System.out.println(); System.out.print("Enter x: "); x = readInt(); System.out.print("Enter y: "); y = readInt(); if (y == 2*x + 3) { System.out.println("This point DOES lie on the line."); } else { System.out.println("This point DOES NOT lie on the line."); } // example #2: Another 'if/else' statement System.out.println(); System.out.println("#2. Another 'if/else' statement testing if number"); System.out.println(" is even or odd"); System.out.println(); System.out.print("Enter x: "); x = readInt(); if (x % 2 == 0) { System.out.println("That number is EVEN"); } else { System.out.println("That number is ODD."); } // example #3: An 'if/else-if/else' statement System.out.println(); System.out.println("#2. An 'if/else-if/else' statement testing if number"); System.out.println(" is positive, negative, or zero."); System.out.println(); System.out.print("Enter x: "); x = readInt(); if (x > 0) { System.out.println("That number is POSITIVE"); } else if (x < 0) { System.out.println("That number is NEGATIVE."); } else { System.out.println("That number is ZERO."); } } /////////////////////////////////// // readString, readInt, readDouble /////////////////////////////////// public static String readString() { java.io.InputStreamReader isr = new java.io.InputStreamReader(System.in); java.io.BufferedReader d = new java.io.BufferedReader(isr); try { return d.readLine(); } catch (Exception e) { return "error"; } } public static int readInt() { return Integer.parseInt(readString()); } public static double readDouble() { return Double.valueOf(readString()).doubleValue(); } }