【问题标题】:numbers from string to char array to int array从字符串到 char 数组到 int 数组的数字
【发布时间】:2014-05-01 01:47:58
【问题描述】:

我有一个字符串输入,我正在尝试将其转换为字符数组,然后以允许我在信用卡程序中使用它们的方式存储该数组中的数字。这就是我目前正在尝试的方式。

我目前在以下位置收到空指针异常:

charDigits[x - invalid] = charInput[x];

我需要能够从字符串输入中使用信用卡算法中的整数。

public class testFunction {
    private char[] charInput;
    private char[] charDigits;
    private int[] intInput;
    private int invalid = 0;
    private String input = "125-6543-3356";

    public testFunction()
    {
        charInput = input.toCharArray();

        for(int x = 0; x < charInput.length; x++)
        {
            if (charInput[x] == '0' || charInput[x] == '1' || charInput[x] == '2' || charInput[x] == '3' || charInput[x] == '9' ||
                charInput[x] == '4' || charInput[x] == '5' || charInput[x] == '6' || charInput[x] == '7' || charInput[x] == '8')
            {               
                charDigits[x - invalid] = charInput[x];
            }
            else
            {
                invalid++;
            }
            System.out.println("charDigits: " + x + ": " + charDigits[x] );
        }

        for(int i = 0; i < charDigits.length; i++)
        {
            intInput[i] = Integer.parseInt(charDigits[i] + "");
        }
    }

        public static void main(String[] args)
        {
            testFunction test = new testFunction();
        }
}

【问题讨论】:

  • 尝试使用if(c &gt;= '0' &amp;&amp; c &lt;= '9') 之类的东西,而不是将所有|| 链接在一起。如您所见,here 09 的代码点是连续的。

标签: java arrays string char integer


【解决方案1】:

我没有看到你在任何地方初始化charDigits。它的初始值为null,因此像charDigits[i] 一样访问它会引发NPE(您应该能够根据NullPointerException 的文档轻松推断出这一点)。您需要先将 charDigits 初始化为一个大小应为任意大小的数组(看起来最大大小将是 charInput.length):

charDigits = new char[charInput.length];

但是,为了使您的其余逻辑正常工作,您还需要跟踪charDigits 中有多少位实际有效(因为最终它可能比charInput 短)。你有很多选择:

  • 考虑在肯定情况下使用valid++ 而不是在否定情况下使用invalid++,并按charDigits[valid] 而不是[x - invalid] 进行索引。在循环结束时,valid 将包含复制到charDigits 的字符数,intInput 可以相应地初始化。
  • 由于charDigits的元素将被初始化为0,当charDigits[i] == 0时停止复制到intInput
  • charDigits 使用动态数组(例如ArrayList&lt;Character&gt;)并根据需要追加。
  • 使用StringBuilder 或其他名称代替charDigits,并根据需要附加。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-10-05
    • 2017-06-15
    • 2016-06-11
    • 2016-02-05
    • 2018-05-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多