gpt4 book ai didi

java - 在子类的函数中使用字符串在 Java 中获取 null

转载 作者:行者123 更新时间:2023-12-01 14:29:05 27 4
gpt4 key购买 nike

我最近一直在学习 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)

这里有一个明显的(对大多数人来说)问题,但只有当您经常使用对象时才会明显。

最佳答案

据我所知,您将 reducerFractions 作为 String 参数 a 传递到 FractionReducer 中。因此,如果您将对 reducerFractions 的引用替换为对 a 的引用,它应该适合您。像这样:

     public void setFraction(String a)
{
System.out.println(a);
//Right here it's saying it's null, I don't understand why...
String[] stringReducedFraction = a.split("/");
double numerator = Float.valueOf(stringReducedFraction[0]);
double denominator = Float.valueOf(stringReducedFraction[1]);
//split up the string here for other uses
}

使字符串 protected 且静态并不是真正的正确方法。如果您在 FractionReducer 中需要它,您应该将其传入。

关于java - 在子类的函数中使用字符串在 Java 中获取 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16959366/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com