if statements
The if statement allows you to check for conditions.
Examples:
Example 1:
// A short console based Java program is shown below that
// demonstrates how you might use an if statement
import java.util.Scanner;
public class Sample3 {
public Sample3() {
}
public static void main(String[] args) {
Scanner scan = new Scanner (System.in);
System.out.println("Slope of a Line");
System.out.println();
System.out.println();
System.out.print("Enter x1 ");
double x1 = scan.nextDouble();
System.out.print("Enter y1 ");
double y1 = scan.nextDouble();
System.out.println();
System.out.print("Enter x2 ");
double x2 = scan.nextDouble();
System.out.print("Enter y2 ");
double y2 = scan.nextDouble();
System.out.println();
System.out.println();
if (x2 != x1)
{
double slope = (y2-y1)/(x2-x1);
System.out.println("The slope of the line is " + slope);
}
System.out.println();
System.out.println();
}
}
Example 2:
// A short console based Java program is shown below that
// demonstrates how you might use an if else statement
import java.util.Scanner;
public class Sample3 {
public Sample3() {
}
public static void main(String[] args) {
Scanner scan = new Scanner (System.in);
System.out.println("Slope of a Line");
System.out.println();
System.out.println();
System.out.print("Enter x1 ");
double x1 = scan.nextDouble();
System.out.print("Enter y1 ");
double y1 = scan.nextDouble();
System.out.println();
System.out.print("Enter x2 ");
double x2 = scan.nextDouble();
System.out.print("Enter y2 ");
double y2 = scan.nextDouble();
System.out.println();
System.out.println();
if (x2-x1==0)
{
System.out.println("The slope of the line is undefined");
}
else
{
double slope = (y2-y1)/(x2-x1);
System.out.println("The slope of the line is " + slope);
}
System.out.println();
System.out.println();
}
}