对于如何从 if 语句中提取值感到非常困惑
所以基本上我有这个 if 语句:
int md; // md = marriage deduction
if (married == 'M'){
md = 750;
System.out.println("Deduction for Being Married: " + md);
}
else if (married == 'S'){
md = 500;
System.out.println("Deduction for Being Single: " + md);
}
我真的很困惑如何从该 if 语句中提取 md 的值。我必须在 if 语句之后根据 md 的值计算另一个整数,但是当我尝试这样做时,md 未定义并显示为错误。像这样:
int total = balance - md - ad
Balance 和 ad 工作正常,因为我不必为它们使用 if 语句,但 md 不会有值。该错误表明它是未定义的,因为我从未在 if 语句之外初始化它,我只是想知道如何从 if 语句中获取 md 的值。非常感谢您的帮助。
So basically I have this if statement:
int md; // md = marriage deduction
if (married == 'M'){
md = 750;
System.out.println("Deduction for Being Married: " + md);
}
else if (married == 'S'){
md = 500;
System.out.println("Deduction for Being Single: " + md);
}
And I'm really confused about how to basically extract the value of md from that if statement. I have to, right after this if statement, calculate another integer based on the value of md, but when I try to do so, md is undefined and shows up as an error. Like this:
int total = balance - md - ad
Balance and ad work fine because I didn't have to use if statements for them, but md won't have a value. The error says that it's undefined which I get because I never initialized it outside of the if statement, I'm just wondering how to get the value of md out of the if statements. Thank you so much for help.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
md
未定义,因为当您声明它时,您没有设置它的值。如果married
不是M
或S
,则md
未定义。否则,md
应保留您分配给它的任何值,因为它超出了if
语句的范围。只需添加一个
else
子句即可将md
设置为零:或者,您也可以将
md
初始化为零。我建议两者都做:md
is undefined because when you declare it, you don't set its value. Ifmarried
is notM
orS
, thenmd
goes undefined. Otherwise,md
should retain whatever value you assign it because it is outside of theif
statement's scope.Just add an
else
clause to setmd
to zero:Alternatively, you could just initialize your
md
to zero. I recommend doing both:我会为这些答案添加一个附录。
或者,您可能想探索使用枚举
I would add an adendum to these answers.
Alternatively you might want to explore using enums
你对已婚的价值几乎肯定不是M或S,因此你没有达到你的陈述的任何一个分支,并且md永远不会被定义。
Your value for married is almost certainly not M or S, thus you're hitting neither branch of your statement and md is never being defined.
如果已婚不是“M”或“S”,则 md 将是未定义的。
if married isn't 'M' or 'S', then md will be undefined.
您遇到的情况是
married
既不是S
也不是M
...因此添加最后一个else
来设置它为零。或者在整个 if 语句之前执行此操作...
或者您有小写的
s
或m
,它们不符合区分大小写的条件You have a condition where
married
is neitherS
norM
... so add a finalelse
to set it to zero.Or do it before the entire if statement...
Or you have lower case
s
orm
which fails a case sensitive condition假设这是我们正在讨论的 JAVA,并且 married 是一个 String 对象,您应该使用 .equalsTo 来比较它们:
Assuming this is JAVA we are talking about and married is a String object You should compare them by using .equalsTo: