简体   繁体   English

toString方法打印空变量,无法理解为什么(Java)

[英]toString method printing null variables, cant understand why (Java)

I haven't found any help on here so I'm gonna just ask. 我在这里找不到任何帮助,所以我只想问。

public  Ride(String n, int tr, double hr , int nr){
    String name = n;
    int ticketsRequired = tr;
    double heightRequirement = hr;
    int numberOfRiders = nr;
}

public String toString(){

    String info;

    info = this.name + " Requiring " + this.ticketsRequired + 
            " tickets with a height restriction of " +       heightRequirement;

    return info;
}

That is in once class, then i try to call it in a main method in another program within my package via this: 这是一次类,然后我尝试通过这个在我的包中的另一个程序中的main方法中调用它:

r1 = new Ride("Death run",0, 5.2, 5);
System.out.println( r1.toString());

Which will return this 哪个会归还这个

null Requiring 0 tickets with a height restriction of 0.0

I'm sure that I'm missing something simple but this is driving me insane. 我确信我错过了一些简单但却让我疯狂的事情。

You're shadowing your instance variables in your constructor : 您在构造函数中隐藏了实例变量:

public Ride(String n, int tr, double hr , int nr){
    name = n;
    ticketsRequired = tr;
    heightRequirement = hr;
    numberOfRiders = nr;
}

Using this with a field in the constructor is not required here, but it is a good pratice as they are often shadowed by the constructor's parameters (see using the this keyword ). 使用this与构造这里不需要一个领域,但它是一个良好的初步实践,因为他们往往是由构造函数的参数阴影(请参阅使用this关键字 )。

Here's a version using the this keyword: 这是使用this关键字的版本:

public Ride(String n, int tr, double hr , int nr){
    this.name = n;
    this.ticketsRequired = tr;
    this.heightRequirement = hr;
    this.numberOfRiders = nr;
}

You are treating the variables like if they were instance variables, however you have declared them locally inside the constructor. 您正在处理变量,如果它们是实例变量,但是您已在构造函数内部声明它们。 Therefore, once it gets out of the scope you declared them in (the constructor), the value of the String object will be null and the value of the int and double variables will be 0 (since it's the default value). 因此,一旦它超出了你在(构造函数)中声明它们的范围, String对象的值将为null,int和double变量的值将为0(因为它是默认值)。

I think this is how you want your class definition: 我想这就是你想要你的类定义:

public class Ride
{
  String name;
  int ticketsRequired;
  double heightRequirement;
  int numberOfRiders;

  public  Ride(String n, int tr, double hr , int nr){
    name = n;
    ticketsRequired = tr;
    heightRequirement = hr;
    numberOfRiders = nr;
  }

  public String toString(){

    String info;

    info = this.name + " Requiring " + this.ticketsRequired + 
        " tickets with a height restriction of " + this.heightRequirement;

    return info;
  }
}

EDIT: fixed a minor problem in the code snippet 编辑:修复了代码段中的一个小问题

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM