我编写了这段代码但得到了NullPointerException

时间:2014-02-19 15:57:24

标签: java arrays nullpointerexception

 import java.io.*;
 import java.util.Scanner;
 import java.math.*;

 class Sort {

 public static void main(String args[]) {

    class gint {
        int N, n, s;
        int ggn[];
    }

    gint gginta=new gint();
    gint ggintb=new gint();
    gint ggintc=new gint();

    int i=0;
    int j=0;
    char c[];
    String ss;
    String sggn;
    String sggnrev="";


    System.out.println("enter the number of maximum digits of the number");
    Scanner scan=new Scanner(System.in);
    gginta.N=scan.nextInt();
    System.out.println("enter the number exact digits of the number ");
    gginta.n=scan.nextInt();
    System.out.println("enter the sign of the number");

    System.out.println("enter the number");
    sggn=scan.next();

    char temp[];
    int l=sggn.length();

    for(j=l-1; j >= 0; j--) {
        sggnrev= sggnrev+sggn.charAt(j);
    }
    int x= Integer.parseInt(sggn);
    System.out.println(sggnrev);
    System.out.println(sggn.length());
    int h;
    System.out.println(sggn.length());

    for (int f=0;f<=sggn.length()-1;f++) {
        System.out.println(f);
        double y=(int) (x/Math.pow(10, f));
        double z=(int) (x/Math.pow(10, f+1));
        double w= y-(z*10);
        System.out.println("power"+i+"= "+(int) y +"-"+(int)z*10+"="+w);
        h= (int)  w;

        gginta.ggn[f]=h;

        System.out.print(gginta.ggn[l-1]);
        l--;
    }
    for (i=0;i<=sggn.length()-1;i++) {          
        if (sggn.length()!=gginta.n) {
            System.out.println("number not in range....enter the number again ... ");
            do {
                System.out.println("number not in range....enter the number again ... ");           
                System.out.println("enter the number");
                sggn=scan.next();       
            } while (sggn.length()!=gginta.n);
        }
    }
}

此代码基本上将数字作为字符串,我的目标是获取字符串的每个索引并将其值传递给整数数组的索引,这样我的数字就在整数数组中,并且每个索引都是数组表示数字的数字

2 个答案:

答案 0 :(得分:0)

只需在gint类中初始化ggn数组:

int ggn[] = new int[5];

否则程序将取消引用具有空值的字段

gginta.ggn[f]=h;

答案 1 :(得分:-1)

始终使用int x = Integer.parseInt(sggn);在try-catch块中

int x =0;

try {
x= Integer.parseInt(sggn);
}catch(NumberFormatException ex) {
 //handle exception:
 x =0;
}