简体   繁体   English

我在加粗的代码行中收到 NULL 指针异常? 我究竟做错了什么?

[英]I'm getting a NULL POinter Exception at the boldened lines of code! What am I doing wrong?

public class kmeansgeneral {
    public static void main(final String args[]) throws Exception {

        int words = 0;
        int chars = 0;
        int lines = 0;

        String s, sp1;
        StringTokenizer st;
        final ArrayList<Double> x = new ArrayList<Double>();

        final FileReader fr = new FileReader("G:/t1.txt");
        final BufferedReader buf = new BufferedReader(fr);

        // Counting number of words and lines
        while ((s = buf.readLine()) != null) {
            lines++;
            st = new StringTokenizer(s, " ,;:.");

            while (st.hasMoreTokens()) {

                words++;
                s = st.nextToken();
                chars += s.length();

                final Double y = new Double(s);
                x.add(y);

            }

        }

        System.out.println("Word Count : " + words / lines);
        System.out.println("Line Count : " + lines);
        // Counting and printing number of words and lines ENDS

        Double ct[] = new Double[0];
        ct = x.toArray(ct);

        // Input array, values to be read in successively, float
        // double[][] indat = new double[lines][lines*words];
        final double[][] indat = new double[10][10];
        int inval = 0;

        final BufferedReader buf1 = new BufferedReader(new InputStreamReader(System.in));
        System.out.print("Enter K-Value : ");
        sp1 = buf1.readLine();

        final Integer ky = new Integer(sp1);
        final int k = ky;

        System.out.println("K ==  " + k);

        // Now read in input array values, successively

        for (int i = 0; i < lines; i++) {
            for (int j = 0; j < words / lines; j++) {

                indat[i][j] = ct[inval];
                inval++;

                System.out.print(indat[i][j]);
                System.out.print("\t");
            }
            System.out.println();
        }


        // Initial Clusters
        System.out.println("   ");
        System.out.println(k + " seed  points ");

        final double[][] Clusters = new double[k][lines * words];
        // double[][] calcnt = new double[lines][words];
        final double[][] calcnt = new double[1000][1000];
        final double[][] array = new double[k][lines * words];

        System.out.println("Clusters==>");
        // int pos=0;
        for (int i = 0; i < k; i++) {
            for (int j = 0; j < words / lines; j++) {

                Clusters[i][j] = indat[i][j];
                // pos= j;

                System.out.print(Clusters[i][j]);
                System.out.print("\t");
            }
            System.out.println();

        }
        System.out.println("PRINTING VECTOR ELEMENTS:");
        final Vector FinalClusters[][] = new Vector[100][100];

        for (int i = 0; i < k; i++) {
            for (int j = 0; j < words / lines; j++) {
                final String tempString = String.valueOf(Clusters[i][j]);
                FinalClusters[i][j].add(tempString);
            }

        }

        // Inital Cluster Array
        System.out.println("Initial Cluster Array");
        int b = 0;
        final double[] arr = new double[2000];

        for (int i = 0; i < k; i++) {
            for (int j = 0; j < words / lines; j++) {

                arr[b] = Clusters[i][j]; // = indat[i][j];
                System.out.print(arr[b]);
                System.out.print("\t");
                b++;
            }

        }
        System.out.println();


        System.out.println("Centroids");

        for (int i = 0; i < k; i++) {
            for (int j = 0; j < words / lines; j++) {

                calcnt[i][j] = (Clusters[i][j] + indat[k][j]) / 2;

                System.out.print(calcnt[i][j]);
                System.out.print("\t");

            }

        }

        // Claculate Distances

        // System.out.println("MAGIC # 3");

        final double[] dist = new double[k];

        for (int i = 0; i < k; i++) {

            double dis = 0;
            for (int j = 0; j < words / lines; j++) {

                dis = dis + (Math.pow(Clusters[i][j] - indat[k][j], 2));

            }
            dist[i] = (Math.sqrt(dis));
            System.out.println("From Cluster K = " + i + "\t" + "Distance" + dist[i]);
        }

        System.out.println("To Find Minimum Distance ");

        double min = dist[0];

        int y = 0;

        for (int m = 0; m < k; m++) {

            if (dist[m] < min) {
                min = dist[m];
                y = m;
            }
        }
        System.out.print("Min Value =" + min + "\t" + "For Cluster :" + y);

        System.out.println();
        System.out.print("Added Cluster =");
        final double[] temp = new double[lines * (words / lines)];

        for (int j = 0; j < words / lines; j++) {

            temp[j] = indat[k][j];

            System.out.print(temp[j]);
            System.out.print("\t");

        }
        System.out.println();

        final Vector[] vector = new Vector[k];
        for (int i = 0; i < k; i++) {
            vector[i] = new Vector<Object>();
        }

        for (int i = 0; i < words / lines; i++) {
            vector[y].add(String.valueOf(temp[i]));
        }

        System.out.println(Arrays.toString(vector));


    }
}

First you should redit your post to make it more clear what the problem is.首先,您应该重新编辑您的帖子,以更清楚地说明问题所在。

Then remove all irrelevant code.然后删除所有不相关的代码。

Then look at your stacktrace, it should say what line is wrong, that line you should post.然后看看你的堆栈跟踪,它应该说哪一行是错误的,那一行你应该发布。

I guess its the one with the ** otherwise your code would not compile我猜它是带有 ** 的,否则你的代码将无法编译

so i assume its this line:所以我假设它的这一行:

      FinalClusters[i][j].add(tempString);//is it this line ?
      // where did you initialise FinalClusters[i][j] ??
      // maybe you first need FinalClusters[i][j] = new Vector(); 

if it is then your error is that you did initiliase the array but not each individual element in the array.如果是,那么您的错误是您确实初始化了数组,但不是数组中的每个单独元素。

Sidenote: Do you really need that array of Vectors?旁注:你真的需要那个向量数组吗?

I ran your code on the following input file:我在以下输入文件上运行了您的代码:

t1.txt: t1.txt:

123
234
345
34456 

Output: Output:

Word Count : 1
Line Count : 4
Enter K-Value : 3
K ==  3
123.0   
234.0   
345.0   
34456.0 

3 seed  points 
Clusters==>
123.0   
234.0   
345.0   
PRINTING VECTOR ELEMENTS:
Exception in thread "main" java.lang.NullPointerException
    at test.kmeansgeneral.main(kmeansgeneral.java:106)

That's this bit of code:就是这段代码:

System.out.println("PRINTING VECTOR ELEMENTS:");
final Vector FinalClusters[][] = new Vector[100][100];

for (int i = 0; i < k; i++) {
    for (int j = 0; j < words / lines; j++) {
        final String tempString = String.valueOf(Clusters[i][j]);
        // NPE OCCURS IN THE LINE BELOW
        FinalClusters[i][j].add(tempString);
    }
}

The problem is the array 'FinalClusters' contains null values, not empty Vectors.问题是数组“FinalClusters”包含 null 值,而不是空向量。 So here's a fix, add the following lines above the line where the error occurs:所以这是一个修复,在发生错误的行上方添加以下行:

if (FinalClusters[i][j] == null) {
    FinalClusters[i][j] = new Vector();
}

Then the output is:那么output就是:

Word Count : 1
Line Count : 4
Enter K-Value : 3
K ==  3
123.0   
234.0   
345.0   
34456.0 

3 seed  points 
Clusters==>
123.0   
234.0   
345.0   
PRINTING VECTOR ELEMENTS:
Initial Cluster Array
123.0   234.0   345.0   
Centroids
17289.5 17345.0 17400.5 From Cluster K = 0  Distance34333.0
From Cluster K = 1  Distance34222.0
From Cluster K = 2  Distance34111.0
To Find Minimum Distance 
Min Value =34111.0  For Cluster :2
Added Cluster =34456.0  
[[], [], [34456.0]]

I don't have a clue what this is supposed to do, so can't tell if this is right.我不知道这应该做什么,所以无法判断这是否正确。 At least no exception is thrown anymore.至少不再抛出异常。

Let me guess: You're probably getting this error debugging this code in eclipse or some editor that doesn't make available a console to the jvm.让我猜猜:您可能在 eclipse 或某些无法为 jvm 提供控制台的编辑器中调试此代码时遇到此错误。

If this is the case then you'd probably hit a nullpointer at sp1 = buf1.readLine();如果是这种情况,那么您可能会在sp1 = buf1.readLine();处遇到空指针。

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

相关问题 空指针异常,我无法弄清楚我在做什么错 - Null Pointer Exception, I can't figure out what I am doing wrong 我收到看似简单的 Java 代码的奇怪错误。 我在这里做错了什么? - I'm getting weird errors for seemingly simple Java code. What am I doing wrong here? 为什么会出现空指针异常 - Why am I getting a null pointer exception 为什么我会收到Null指针异常? - why am i getting Null Pointer Exception? 我在 android 中收到 null 指针异常 - I am getting null pointer exception in android 请我在这段代码中做错了什么 - Please what am i doing wrong in this code 我正在向某人的现有Swing代码添加一个组合框。 我在这里做错了什么? - I'm adding a combobox to someone's existing Swing code. What am I doing wrong here? 我的arraylist出现IndexOutOfBoundsException,我在做什么错? - I'm getting an IndexOutOfBoundsException with my arraylist, what am I doing wrong? 我有一个空指针异常,我不确定它在我的代码中的位置 - I am having a null pointer exception and i'm not sure where it is in my code 我正在尝试读取一个简单的 Json 文件,但我保存了一个 null。 我究竟做错了什么? 我的 json 仅包含 4 个字段 - I'm trying to read a simple Json file but im getting saved a null. What am i doing wrong? My json contains only 4 fields
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM