0
public class Practica2 {

public static void main(String[] args) {  

Vector v = new Vector(3); //create an empty Vector vec with an initial capacity of 3   
v.setpos(0,1); //set 0 at 1 index position
v.setpos(1,2); //set 1 at 2 index position
v.setpos(3,3); //set 3 at 3 index position
v.print();

这是我的类向量:

package practica2;
public class Vector {
//Atributes
private double[] values;
private int dim;

//Methods 
public Vector(int dim) {
    this.dim = dim;

}

public void setpos(int i, int value) {
    values[i] = value;


}

public void print() {
    for (int i = 0; i <= dim; i++) {
        System.out.println(values);


    }

我收到这个错误,我不知道如何解决它,我只是浪费了 2 个小时,我是 Java 新手。

运行:practica2.Vector.setpos(Vector.java:24) 处的线程“main”java.lang.NullPointerException 中的异常 practica2.Practica2.main(Practica2.java:23) Java 结果:1 BUILD SUCCESSFUL(总时间:0秒)

4

1 回答 1

0

A null pointer exception occurs in java when you try to use an object without first initializing it. You never initialize the values array. Add this into your constructor (I'm assuming that you wanted it to be length dim:

values = new double[dim];

That will fix one error, and probably give you an array index out of bounds error. In java, arrays are 0-indexed. That is, if you have an array of length 3, the valid indeces of that array are 0, 1, and 2. NOT 3. You should change

v.setpos(3,3);

to

v.setpos(2,3);

You are also calling println(values) which prints using the Array's toString() method (basically, it's garbage). You'll want to change the print statement to System.out.println(values[i])

Now your program should run correctly.

As a side note, you dont have to save the value of dim. You can use instead values.length. (In your print method, for example).

于 2013-11-08T15:09:16.830 回答