Java 为什么string.equals(“astring”)不起作用?
如果我调用Java 为什么string.equals(“astring”)不起作用?,java,Java,如果我调用getMatInt(),为什么我在将例如“黑曜石”发送到测试(字符串pStr)后不得到20 也尝试过。toString()在所有字符串去极化之后,也声明了例如“黑曜石”为新字符串。什么都不管用 getBonus返回0而不是20/30/。 我已经试过“黑曜石”和“黑曜石”,但都不适合我 public class test { private String str; private int matInt; private int bonus; private int mag
getMatInt()
,为什么我在将例如“黑曜石”发送到测试(字符串pStr)
后不得到20
也尝试过。toString()
在所有字符串去极化之后,也声明了例如“黑曜石”为新字符串。什么都不管用
getBonus返回0而不是20/30/。
我已经试过“黑曜石”和“黑曜石”,但都不适合我
public class test
{
private String str;
private int matInt;
private int bonus;
private int magic;
public test(int pMagic, String pStr)
{
int magic = pMagic;
str = pStr;
}
private void materialEquals()
{
if(str.equals("Obsidian"))
{
matInt = 20;
}
.....
}
private void calcBonus()
{
materialEquals();
bonus = magic * matInt;
}
public int getBonus()
{
calcBonus();
return bonus;
}
}
尝试:
在构造函数中没有这样做的原因:str=newstring(pStr)
,只需使用str=pStr
事实上,您最好在构造函数中设置matInt
:
public test(String pStr)
{
str = pStr;
materialEquals();
}
根据您拥有的材质数量,您可能希望研究使用枚举
编辑后确定:
public int getBonus()
{
calcBonus(); //bonus won't be calculated otherwise
return bonus;
}
进一步编辑后:
您的构造函数错误,您没有初始化intmagic
。请尝试此构造函数
public test(int pMagic, String pStr)
{
this.magic = pMagic; //int magic = pMagic was a new variable only in the constructor scope
this.str = pStr;
calcBonus();
}
您还可以计算构造奖金。您需要调用materialEquals()
,以便20
可以在等于比较时分配给matInt
,因为整数在声明时总是初始化为默认值0
因为您从未调用materialEquals
,至少在此代码中是这样。忘记添加它,它仍然不起作用假设编辑后它仍然不起作用,您在什么上下文中调用getMatInt()
?我们能看到你的主方法或者你调用它的代码块吗?花点时间把它们放在一起,因为你提供的代码是不完整的,我们无法帮助你。如果你把一个简短的例子放在一起,说明我们可以运行的行为,我们可以解释为什么。作为一个额外的好处,仅仅是组装一个SSCCE是一个很好的调试工具,并且常常有助于自己发现bug。有些东西是你没有展示出来的,导致它无法工作。由于代码位于stands(假设您调用materialEquals()
),当您调用getMatInt()
时应该返回20,并且在这里编译时返回20。我忘了再次添加该方法,抱歉。更新了我的代码,对我来说仍然不起作用。那很有效,谢谢。我没有奇怪地得到一个NPE。事实上,这很有意义,int不能为null,它默认为0。
public test(int pMagic, String pStr)
{
this.magic = pMagic; //int magic = pMagic was a new variable only in the constructor scope
this.str = pStr;
calcBonus();
}