给定代码中的异常(java)
我有一个测试程序,我看到一个空指针异常。我需要帮助找出如何解决它,并想知道根本原因给定代码中的异常(java),java,nullpointerexception,Java,Nullpointerexception,我有一个测试程序,我看到一个空指针异常。我需要帮助找出如何解决它,并想知道根本原因 public class test { private static void practice(String[] words) { int vowelPosition = 0; int consonantPosition = 0; char[] vowel = (char[]) null; char[] consonant = (cha
public class test {
private static void practice(String[] words) {
int vowelPosition = 0;
int consonantPosition = 0;
char[] vowel = (char[]) null;
char[] consonant = (char[]) null;
for (int i = 0; i < words.length; i++) {
int currentWordLength = words[i].length();
for (int j = 0; j < currentWordLength; j++) {
if (words[i].charAt(j) == 'a' || words[i].charAt(j) == 'e'
|| words[i].charAt(j) == 'i'
|| words[i].charAt(j) == 'o'
|| words[i].charAt(j) == 'u') {
consonant[j] = 'n';
vowel[j] = words[i].charAt(j);
vowelPosition = j;
System.out.println(j + "At this position is "
+ vowel[vowelPosition]);
} else {
vowel[j] = 'n';
consonant[j] = words[i].charAt(j);
consonantPosition = j;
System.out.println(j + " At this position is "
+ consonant[consonantPosition]);
}
}
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
String[] words = { "harpreet" };
practice(words);
}
}
公共类测试{
私有静态无效实践(字符串[]字){
int元音位置=0;
int辅音位置=0;
char[]元音=(char[])空;
char[]辅音=(char[])空;
for(int i=0;i
我还尝试调试它,发现内部循环引发异常。您已分配:
char[] vowel = (char[])null;
你指的是:
vowel[j] = words[i].charAt(j);
由于元音
数组是null
,这就是为什么会得到NPE
为了修复它,您需要为元音
数组分配一个非空值:
char[] vowel = new char[100]; //for example
您应该为元音和辅音分配内存,否则它们是空的。您可以这样做:
char[] vowel = (char[])null;
char[] consonant = (char[])null;
consonant.add('n');
vowel.add(words[i].charAt(j));
如果您不知道应该为变量分配多少内存,可以使用ArrayList,它可以自动分配内存。将上面的两行替换为下面的两行:
ArrayList<Character> vowel = new ArrayList<Character>();
ArrayList<Character> consonant = new ArrayList<Character>();
改变这两行
char[] vowel = (char[]) null;
char[] consonant = (char[]) null;
到
由于使用空值初始化这两个数组,您将获得NPE。初始化这两个数组的方式是错误的
char[] vowel = (char[])null;
char[] consonant = (char[])null;
您必须为非空值的元音和辅音分配空间。您能给我们显示一个精确的堆栈跟踪吗?为了将来的参考,请在您询问错误/异常时始终提供堆栈跟踪。讨厌这种向下投票。。!!但是我给它赋值了。。!!元音[j];值得一提的是辅音to:)@Gurjit在创建数组之前,不能使用它<代码>字符[]字符=新字符[10]@Gurjit,您的任务是分配元素,而不是数组。在将值指定给第j个元素之前,需要定义元素的大小array@christopher无法声明它,,,必须初始化它,,,否则给出错误。。!!
char[] vowel = (char[])null;
char[] consonant = (char[])null;