用Java中的距离计算器变量初始化问题

问题描述 投票:0回答:1

当我认为我在底部显示的代码中的 if 语句中初始化了变量“距离”时,变量“距离”并未初始化。那么你能给出一个关于如何修复它的解决方案吗,因为我是 Java 新手(输出在页面底部)

我的代码:

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);
    }
}

输出: Main.java:49:错误:变量距离可能尚未初始化 System.out.print(距离); ^ 1 个错误

我期望所有变量都能初始化并正常工作,这样它就可以知道一个点到另一点有多远。

java initialization
1个回答
0
投票

尝试在第 9 行声明距离变量:

double distance = 0.00;

© www.soinside.com 2019 - 2024. All rights reserved.