[英]How do I fix Null Pointer Exception?
我正在尝试计算字符串中的元音数量。 问题是它正确编译,但是当我运行它时,命令窗口在CountVowels.main( CountVowels.java:25 )中显示“线程中的异常'主' java.lang.NullPointerException” 。
import javax.swing.JOptionPane;
public class CountVowels
{
public static void main(String[] args)
{
String thingy = JOptionPane.showInputDialog("Please enter a sentence, and I will count the vowels.");
int count = 0;
char[] chars = new char[thingy.length()];
String[] letters = new String[thingy.length()];
for(int i = 0; i < thingy.length(); ++i)
{
chars[i] = thingy.charAt(i);
}
for(int i = 0; i < letters.length; ++i)
{
letters[i].valueOf(chars[i]);
}
for(int i = 0; i < chars.length; ++i)
{
if(letters[i].equals("a") || letters[i].equals("e") || letters[i].equals("i") || letters[i].equals("o") || letters[i].equals("u"))
{
++count;
}
}
System.out.println("There are " + count + " vowels in the string + " + thingy);
}
}
是什么导致这种情况,我该如何修复它,以及如何防止它在将来再次发生?
第25行是我的if语句:
if(letters[i].equals("a") || letters[i].equals("e") || letters[i].equals("i") || letters[i].equals("o") || letters[i].equals("u"))
{
++count;
}
这条线
letters[i].valueOf(chars[i]);
什么也没做。 如果你改成它
letters[i] = String.valueOf(chars[i]);
您将所有letters
元素设置为相应的字符。 这应该修复你的NullPointerException
。
您还可以使用一些正则表达式技巧来保存大量代码:
import javax.swing.JOptionPane;
public class CountVowels
{
public static void main(String[] args)
{
String input = JOptionPane.showInputDialog("Please enter a sentence, and I will count the vowels.");
String[] letters = input.split("(?<=.)(?=.)");
int count = 0;
for(int i = 0; i < letters.length; i++)
{
if(letters[i].matches("[aeiou]"))
{
count++;
}
}
System.out.println("There are " + count + " vowels in the string + " + input);
}
}
请尝试使用此代码:
letters[i] = "" + chars[i];
此外,您不需要经历创建从String到chars到String的新数组的所有麻烦。 有关从String访问每个字符的更多信息,请阅读此问题(这样您就可以检查thingy
对象中的字母而无需创建更多数组)
试试这个 :
import javax.swing.JOptionPane;
class CountVowels
{
public static void main(String[] args)
{
String thingy = JOptionPane.showInputDialog("Please enter a sentence, and I will count the vowels.");
int count = 0;
char[] c=thingy.toCharArray();
for(int i = 0; i < c.length; ++i)
{
if(c[i]=='a' || c[i]=='e' || c[i]=='i' || c[i]=='o' || c[i]=='u')
{
++count;
}
}
System.out.println("There are " + count + " vowels in the string + " + thingy);
}
}
输出:
数组letters
为空。 它包含null
值。
您的代码中存在错误。 当您使用String进行操作时,应该使用返回字符串进行进一步处理。请参阅文档
letters [i] = String.valueOf(chars [i]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.