java - 如何从对象访问元素?爪哇
问题描述
我是编程新手,目前是从 java 开始的。我想知道如何访问我创建的对象的元素。我以为我知道怎么做,但它似乎不起作用。我正在从一个方法而不是内部类中构造一个内部类内部的对象。我想知道您是否可以给我一些提示,为什么当我想访问刚刚创建的对象的值时它不起作用。我的意思是可以访问这些值,但它们应该不同于 0。就好像我的构造函数没有传回这些值一样。我确实将我的程序进行了调试,并且传递给构造函数的值是 0、2、2。谢谢。
public class puzzle{
public class Build{
int nb, piece, length;
public Build(int nb, int piece, int length){
//In debug I see that the values are passed, but when I print in the method the values printed are all 0.
nb = nb;
piece = piece;
length = length;
}
}
public void rectangle(String book){
//line of code where I do manipulations
Build box = new Build(beginning, tv, book.length());
System.out.println(box.nb);
System.out.println(box.piece); //should print a value different then 0
System.out.println(box.length); //should print a value different then 0
}
}
解决方案
nb = nb;
这没有任何作用。它将 nb 设置为自身。
这里有 2 个完全不相关的变量。一个被称为int nb;
并且是您Build
班级的一个领域。另一个是方法参数,完全巧合也被命名为nb
.
您要设置字段,使用参数值。
你有两个选择。
停止使用相同的名称。方法参数“优先”(在 java 中:Shadows the field)。
使用
this.nb
which 指的是字段:this.nb = nb;
。
第二种形式是惯用的java。去做。
推荐阅读
- python - 如何从这个网页抓取的 HTML 中提取某些元素
- php - 如何为自动图像优化提取图像路径及其推荐的新尺寸?
- amazon-dynamodb - 使用 DynamoDB 二级索引 AWS SDK 2 Java 异常创建 DynamoDbIndex 对象进行查询
- jquery - 数组的 HTML 元素的选择器
- c++ - Character::BeginPlay() 未被调用
- javascript - 如何检查 ReportControl 对象上是否存在 Reportid 或不使用 *ngif?
- python - 如何从 HTML 中获取带有特定文本的行
- android - Flutter Development (flutter-dev) › 需要紧急帮助....由于 gradle 问题,我无法在 android 设备中运行 Flutter 应用程序并且无法构建 apk
- python - 第一次尝试 python,错误(“IndexError: index 8 is out of bounds for axis 0 with size 8”)和效率问题
- java - JavaFX 异常:内部图形尚未初始化