【问题标题】:I have written this code but getting NullPointerException [duplicate]我已经编写了这段代码,但得到了 NullPointerException [重复]
【发布时间】:2014-02-19 15:57:23
【问题描述】:
 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);
        }
    }
}

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

【问题讨论】:

  • 你有什么问题?你只是在这里转储你的代码。
  • 添加异常的堆栈跟踪
  • 空指针异常将告诉您哪一行代码失败,以及您是如何到达那里的,如果您查看堆栈跟踪。找到那一行,找出那一行上使用了哪些指针,找出它们中的任何一个可能是空的,修复代码。
  • 另外,请阅读如何在 SO 中格式化代码。很难理解您发布的内容。
  • class gint { int N, n, s; int ggn[]; } 真的...?从今天起五天后,祝你好运理解这样的代码。如果您真的认为 Java 语言的命名约定不适合您,至少在您自己的风格中保持一致。其他一切只会导致混乱和混乱。 ;)

标签: java arrays nullpointerexception


【解决方案1】:

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

int ggn[] = new int[5];

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

gginta.ggn[f]=h;

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 2013-06-23
      • 1970-01-01
      • 2018-06-02
      • 2021-04-10
      • 2021-02-06
      • 2022-01-18
      • 2023-01-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多