当前位置: 首页 > 知识库问答 >
问题:

我已经写了这段代码,但得到NullPointerException[重复]

逄俊力
2023-03-14
 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个答案

罗智志
2023-03-14

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

int x =0;

try {
x= Integer.parseInt(sggn);
}catch(NumberFormatException ex) {
 //handle exception:
 x =0;
}
慕容越泽
2023-03-14

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

int ggn[] = new int[5];

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

gginta.ggn[f]=h;
 类似资料: