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.
mdis undefined because when you declare it, you don’t set its value. Ifmarriedis notMorS, thenmdgoes undefined. Otherwise,mdshould retain whatever value you assign it because it is outside of theifstatement’s scope.Just add an
elseclause to setmdto zero:Alternatively, you could just initialize your
mdto zero. I recommend doing both: