Initializing problem with a variable for a distance calculator in Java with if and else statement

51 views Asked by At

The variable 'distance' is not initializing when I think I initialized it in my if statements in the code that is shown in the bottom. So can you give a solution on how to fix it as I am new to Java(output at the bottom of the page)

My code:

import java.util.*;
public class Main
{
    public static void main(String[] args) {
        double a1;
        double a2;
        double b1;
        double b2;
        double distance;
        
        Scanner scan = new Scanner( System.in );
        System.out.print("What number is the 'x' axis of the first check point");
        a1 = scan.nextDouble();
        System.out.print("What number is the 'y' axis of the first check point");
        a2 = scan.nextDouble();
        System.out.print("What number is the 'x' axis of the second check point");
        b1 = scan.nextDouble();
        System.out.print("What number is the 'y' axis of the second check point");
        b2 = scan.nextDouble();
        
        
        if(a1 >= b1 && a2 >= b2)
        {
            distance = Math.sqrt(((a1 - b1) * (a1 - b1)) + ((a2 - b2) * (a2 - b2)));
        }
        if(b1 >= a1 && b2 >= a2)
        {
            distance = Math.sqrt(((b1 - a1) * (b1 - a1)) + ((b2 - a2) * (b2 - a2)));
        }
        if(a1 >= b1 && b2 >= a2)
        {
            distance = Math.sqrt(((a1 - b1) * (a1 - b1)) + ((b2 - a2) * (b2 - a2)));
        } 
        if(b1 >= a1 && a2 >= b2)
        {
            distance = Math.sqrt(((b1 - a1) * (b1 - a1)) + ((a2 - b2) * (a2 - b2)));
        }
        
        System.out.println("************************************************************");
        System.out.println("The distance between the two points is(Units):");
        System.out.print(distance);
    }
}

The output: Main.java:49: error: variable distance might not have been initialized System.out.print(distance); ^ 1 error

I was expecting all variables to initialize and work normally so it could tell how far one point was to another point.

1

There are 1 answers

0
Rajaruban Rajindram On BEST ANSWER

Try declaring variable for distance with initial value as 0.00 at line 9 as below code:

double distance = 0.00;