View Single Post
Old 12-05-2004, 17:48   #6 (permalink)
Datapunter
Pro Punter
 
Datapunter's Avatar
 
Join Date: 23 Oct 2003
Location: Westdorpe
Age: 43
Posts: 5,522
Default Re: lesson23

Original question by Oddsfellow, moved here


Datapunter

I am afraid some of us are still on assignment 2.3 as i have not had much spare time of late. However i cannot seem to print out the Winnings. Could you possibly advise where i went wrong. I know the answers are there but i would just like to know what i did really. Heres my program


public class Lesson2 {
public static void main(String[ ] arguments) {

int Bank = 1000;
int Bet = 100;
int Odds = 3;
int WinLose = 0;
int Winnings = 0;

if (WinLose == 0)
{
Bank = Bank - Bet;
}
else
{
    if (WinLose== 1)
    {
    Bank = (Bank - Bet) + (Bet * Odds);
    }
    else
    {
    Bank = Bank;
    }
}

System.out.println(Bank);
if (WinLose == 0 )
{
Winnings = Winnings - Bet;
}
else
{
    if (WinLose ==1)
    {
    Winnings = (Bet * Odds) - Bet;
    }
    else
    {
    Winnings = Winnings;
    System.out.println(Winnings);
    }
}

} // this bracket is end of method main, see second line
} // this bracket is end of the program, see first line

Thanks


First a note on the brackets.
Java executes the parts after IF and ELSE that are enclosed in the brackets. We use the brackets to group the commands that are part of the IF or ELSE. Now in this case it is not neccesary since there is only one command done. In case of more than one command the brackets in bold should also be there.



lets look at the program from top to bottom
so in this case WinLose is 0,
in the first IF ELSE the part about the bank is done,
the part after the ELSE is skipped,
then we print the Bank,
so far so good,

in the second IF ELSE the first part is done,
winnings = winnings - bet
and then the part after ELSE is skipped.

as you can see, printing winnings on the screen is inside the ELSE part and is therefore not done. move it down one line and it will work.

Also the lines Bank = Bank; and Winnings = Winnings; do not do anything and can be removed. In fact the whole ELSE can be removed and the second IF can even be removed. Have left it for now so you can have a look. If the condition WinLose == 0 is not true then Java continues after ELSE, but you do not need to repeat checking the condition, thats already done.

So the ending becomes like this:


System.out.println(Bank);
if (WinLose == 0 )
{
Winnings = Winnings - Bet;
}
else
{
    if (WinLose ==1)
    {
    Winnings = (Bet * Odds) - Bet;
    }
    else
    {
    Winnings = Winnings;
    }
}
System.out.println(Winnings);
}
}



but this does the same:

System.out.println(Bank);
if (WinLose == 0 )
{
Winnings = Winnings - Bet;
}
else
{
Winnings = (Bet * Odds) - Bet;
}

System.out.println(Winnings);
}
}
Datapunter is offline