【问题标题】:My variables are not initializing properly我的变量没有正确初始化
【发布时间】:2014-09-28 02:36:13
【问题描述】:

在我下面的代码中double getAirSpeeddouble calcPatternwidthdouble calcPatternLength 没有被正确初始化,为什么?

/**
 * holding patterns
 * assignment 1 
 * question 2 
 **/ 

import java.util.Scanner; 

public class StockiColeA1Q2  {

  public static void main(String []args)  {
    Scanner keyboard = new Scanner(System.in);

    double getAirSpeed ;
    double calcPatternWidth;
    double calcPatternLength; 

    System.out.println("That speed is " + getAirSpeed + 
                       "\nHolding pattern width: " + calcPatternWidth +
                       "kms\nHolding pattern length: " + calcPatternLength + "kms");  

  }//main 

  public static double getAirSpeed() {
    Scanner keyboard = new Scanner(System.in); 

    System.out.println("Enter the speed in Knots: "); 
      double knots = keyboard.nextDouble(); //knots given by user 

      return knots*1.852;

  }//get air speed 

  public static double calcPatternWidth(double knots) {

  return (knots/60*Math.PI)*2;

  }//patern width 

  public static double calcPatternLength(double knots) {

    return knots/60 + (knots/60*Math.PI)*2;


  }//pattern width 

}//class

【问题讨论】:

  • 有什么问题?预期的输出是多少?你得到什么,有什么错误吗?请在问题 BODY(不是标题)中澄清它。此外,为您的问题添加标签,特别是代码的语言。
  • 你声明它们,然后不要对它们做任何事情。所以这就是你的答案:如果你想要 in 他们的任何东西,你必须首先让你的代码做到这一点。

标签: java variables


【解决方案1】:

您没有正确初始化 main 中的变量。您显示调用函数并预先分配它们,然后显示它们。我认为您正在寻找的是一个看起来像这样的main

public static void main(String[] args) {
    double getAirSpeed = getAirSpeed();
    double calcPatternWidth = calcPatternWidth(getAirSpeed);
    double calcPatternLength = calcPatternLength(getAirSpeed);

    System.out.println("That speed is " + getAirSpeed + "\nHolding pattern width: " + calcPatternWidth
            + "kms\nHolding pattern length: " + calcPatternLength + "kms");

}// main

上面的代码使用getAirSpeed 作为calcPatternWidthcalcPatternLength 的参数。我猜这就是你想要完成的。

您确实应该在完成后关闭 Scanner 对象,所以我会修改 getAirSpeed() 以在返回之前调用 keyboard.close()

public static double getAirSpeed() {
    Scanner keyboard = new Scanner(System.in);

    System.out.println("Enter the speed in Knots: ");
    double knots = keyboard.nextDouble(); // knots given by user

    keyboard.close();
    return knots * 1.852;

}// get air speed

【讨论】:

    【解决方案2】:

    在这里,我无法看到您在哪里初始化给定变量。由于所有三个变量都是 main 方法的本地变量,因此编译器不会为它们分配默认值。仅创建这些变量的 getter 不会分配该值。如果您在类中的 main 方法之外创建变量,编译器将分配默认值,但您必须将它们设为静态,因为 main 方法是静态的,并且您不能在静态块内使用非静态变量。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-03-10
      • 1970-01-01
      • 2012-03-23
      • 2023-03-27
      • 1970-01-01
      • 2016-10-03
      • 2022-01-02
      • 1970-01-01
      相关资源
      最近更新 更多