我的问题始于第一个do-while循环。我要问“请输入一个介于0到90之间的角度:”,如果用户输入的数字确实介于0到90之间,他们必须输入枪粉量。他们的输入将经过物理计算,如果结果不是“这很成功!”。然后我想让他们返回并再次输入角度和火药。但是事情在while (distance - distance2 != 0 || distance - distance2 != 1 || distance2 - distance != 1); System.out.println("It's a hit!"); 该错误显示:变量distance2可能尚未初始化。 import java.util.*; import java.text.*; public class BombsAway { private static double ZERO_THOUSAND = 1000; private static double KG_TO_VELOCITY = 50; private static double GRAVITY = -9.81; public static void main(String[] args) { Scanner input = new Scanner(System.in); DecimalFormat threeDec = new DecimalFormat("#.##"); Random gen = new Random(); BombsAway distanceAn = new BombsAway(); boolean invalidInput = true; double distance, distance2; System.out.println("Please enter a positive integer seed value: "); while(invalidInput) { try { int seedValue = Integer.valueOf(input.nextLine()); if (seedValue <= 0) { System.out.println("Please enter a positive integer seed value:" + " "); } else { distance = gen.nextDouble() * ZERO_THOUSAND; System.out.println("That target is " + threeDec.format(distance) + "m away."); do { System.out.println("Please enter an angle between 0 and 90 " + "degrees: "); while (invalidInput) { try { double angle = Double.valueOf(input.nextLine()); if (angle < 0 || angle > 90) { System.out.println("Please enter an angle between " + "0 and 90 degrees: "); } else { System.out.println("Please enter the amount of " + "gunpowder in kilograms: "); try { double gunpowder = Double.valueOf(input.nextLine()); //physics part double initialV = gunpowder * KG_TO_VELOCITY; double vX = initialV * Math.cos(angle); double vY = initialV * Math.sin(angle); double airBorn = (-vY - vY) / GRAVITY; distance2 = (vX * airBorn); if (distance > distance2) { double finalDist = distance - distance2; System.out.println("It's " + threeDec.format(finalDist) + "m short."); } else if (distance < distance2) { double finalDist = distance2 - distance; System.out.println("It's " + threeDec.format(finalDist) + "m long."); } } catch(NumberFormatException e) { System.out.println("Please enter the amount of " + "gunpowder in kilograms: "); } } } catch(NumberFormatException e) { System.out.println("Please enter an angle between " + "0 and 90 degrees: "); } } }while (distance - distance2 != 0 || distance - distance2 != 1 || distance2 - distance != 1); System.out.println("It's a hit!"); } } catch(NumberFormatException e) { System.out.println("Please enter a positive integer seed value: "); } } }} 最佳答案 在您的代码中-distance2在条件块之一(在else循环内的while块中)内初始化,在某些情况下可能无法满足您的while或else条件,在这种情况下未被初始化,并且不进行初始化就无法使用Local变量,因此只需使用任何有意义的或必需的默认值将该distance2初始化为:distance2或具有您的代码逻辑可以使用的某些特定值 10-07 17:21