我最近一直在学习 Java,它与大多数其他语言完全不同。我和其他一些人站在那里摸不着头脑,不明白为什么有些东西不起作用,这是我看到的所有问题。这。时间。这令人沮丧和恼火,希望我可以为其他人提供一些启示。
有没有问过自己这个?:
“我一直试图让它工作几个小时,但我似乎看不到它。我试图将字符串“reducerFractions”传递给 FractionReducer 类,但不知何故,当它进入那个类时变为空?
我对Java真的很陌生,这只是我的第二个程序,我不太明白为什么这不起作用......
父类:
public class FractionCalc extends FractionUI
{
//member variables for this class initialized here, all are kept within this class
protected String reducerFractions;
{
/*Paramiters in here math stuff ect*/
finalNum = (int)fin_num;
finalDem = (int)fin_dem;
reducerFractions = finalNum + "/" + finalDem;
//puts these together in a protected string
System.out.println(reducerFractions); //<- testing here shows its working as needed
reducer.setFraction(finalNum, finalDem);
//overloading the function shows it's working for the two ints as ints themselves
reducer.setFraction(reducerFractions);
int rNum = reducer.getResultsNum();
int rDenom = reducer.getResultsDenom();
String debug = rNum + " " + rDenom;
System.out.println(debug);
//right here gives back the correct numbers using an int approach
}
儿童班:
public class FractionReducer extends FractionCalc
{
public void setFraction(String a)
{
System.out.println(reducerFractions);
//Right here it's saying it's null, I don't understand why...
String[] stringReducedFraction = reducerFractions.split("/");
double numerator = Float.valueOf(stringReducedFraction[0]);
double denominator = Float.valueOf(stringReducedFraction[1]);
//split up the string here for other uses
}
//Other stuff
}
终端输出
2/1 //The string prints out fine in the parent class
null//but null in the child?
Exception in thread "main" java.lang.NullPointerException
at FractionReducer.setFraction(FractionReducer.java:25)
at FractionCalc.FractionCalc(FractionCalc.java:73)
at FractionUI.Run(FractionUI.java:47)
at MainP2.main(MainP2.java:19)
这里有一个明显的(对大多数人来说)问题,但只有在您大量使用对象后才会明显。