我做了一个叫Point的课。我在MainActivity上创建一个名为“ A”的对象。 现在,我想要MainActivity上的一些方法,该方法应该读取“ A”的属性,但是这是不可能的。为什么我不能访问Point类的自制对象“ A”? 例如,方法“加法”无法读取对象“ A”的属性“ x”和“ y”。为什么?
public class Point {
public int x;
public int y;
public Map <String, Integer> paths = new HashMap<String, Integer>();
}
ll
public class MainActivity extends AppCompatActivity {
Point A, B, C, D;
int i;
TextView tv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = findViewById(R.id.tv);
Point A = new Point();
A.x = 1;
A.y = 1;
A.paths.put("B", 1);
A.paths.put("C", 2);
addition();
}
private void addition() {
tv.setText(""+A.x);
}
}
编辑:tv.setText(“” + A.x);现在给我一个NullpointerExeption
Caused by: java.lang.NullPointerException: Attempt to read from field 'int com.example.georg.pathfinding.Point.x' on a null object reference
at com.example.georg.pathfinding.MainActivity.addition(MainActivity.java:57)
at com.example.georg.pathfinding.MainActivity.onCreate(MainActivity.java:49)
答案 0 :(得分:1)
尝试此操作将您的 Point A
声明为全局
public class MainActivity extends AppCompatActivity {
Point A, B, C, D;
int i;
TextView tv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = findViewById(R.id.tv);
A = new Point();
A.x = 1;
A.y = 1;
A.paths.put("B", 1);
A.paths.put("C", 2);
addition();
}
private void addition() {
tv.setText(""+A.x);
}
}
答案 1 :(得分:0)
将值传递给您的方法:-
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Point A = new Point();
A.x = 1;
A.y = 1;
A.paths.put("B", 1);
A.paths.put("C", 2);
addition(A.x, A.y);
}
private void addition(int a, int b) {
int i;
i = a + b;
}
}