【问题标题】:Simple java "Classes" and "Methods" questions [closed]简单的java“类”和“方法”问题[关闭]
【发布时间】:2014-01-20 18:37:06
【问题描述】:

考虑一个 Quadratic 类,它维护有关二次表达式 ax^2+bx+c 的信息。

public class Quadratic
{
    private double a;
    private double b;
    private double c;

    /*  Constructor: initializes all instance variables
     */
    public Quadratic(double aVal, double bVal, double cVal)
    {  //code omitted
    }

    /* This method determines and displays the real roots of 
     * the quadratic this.
     */

    public void displayRoots()
    { //code omitted.
    }

    /* Returns the value of this quadratic evaluated at xVal.
    */

    public double calcValue(double xVal)
    { //code omitted.
    }

} //end class

所以问题问了: 完成构造函数 Quadratic,它将实例变量初始化为所提供参数的值。

public Quadratic (double aVal, double bVal, double cVal)
{     

}

【问题讨论】:

  • 你的问题是什么?还是您只是告诉我们该怎么做?
  • 你的意思是:// Please write code for me,而不是所有这些地方的// code omitted
  • @RohitJain 我想他刚刚把他的家庭作业贴在这里了。
  • 你通常如何分配东西?
  • 一点也不清楚用户在问什么。再清楚不过了。既然只提到了一个问题,那这个问题怎么可能是其他问题呢?

标签: java class methods


【解决方案1】:

In this example

class Language {
  String name;

  Language(String t) {
    name = t;
  }

  //rest of code

}

我们有一个名为name的类变量:

  String name;

但是,名称一开始是没有值的,所以我们假设我们将通过参数传递这个值:

Language(String t) {  //everything in the parenthesis are the parameters 

唯一的参数是t。这将由其他一些方法/类传入,但是我们如何处理它呢?我们可能应该将它存储到我们的类变量中:

    name = t;

这样您就可以保存它并将其用于您编写的方法。 您应该能够将相同的逻辑应用于您的作业要求。这里有一些其他资源(网上有很多!):

http://java.about.com/od/workingwithobjects/a/constructor.htm

http://www.cis.upenn.edu/~matuszek/General/JavaSyntax/constructors.html

http://www.javaworld.com/article/2076204/core-java/understanding-constructors.html

http://www.homeandlearn.co.uk/java/class_constructor.html

【讨论】:

  • +1 表示没有为他编写代码。
  • name 不是局部变量。
  • @crush 好点,让我更新
  • 班级成员会更好,但这对提出这个问题的人来说是浪费精力。很明显,他们不想付出努力去学习他们在学校要学的东西。
猜你喜欢
  • 2011-10-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-09-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多