Wednesday, February 28, 2007

Little Java program

My first little java program... after a few tries with the Hello World and reading a book I did my beeting game. It is not a great thing but I need to get used to break problems in parts - the example below doesn't do 100% that.

I need to be able to break each action as much as possible, at the begining I thought it was going to be easy but for this simple example I kept falling into creating one big procedural class. I should be able to break it even more and caught more exception (like entering chars/strings instead of numbers) and will do it after I finish the second book of begining java.

import java.text.NumberFormat;

public class Account {

static int balance;

public Account (int amount) {
balance = amount;
}

public Account () {
balance = 0;
}

public void credit (int betamount){
balance = balance + (2 * betamount);
}

public vo
id debit (int betamount){
balance = balance - betamount;
}

public boolean checkBet (int betamount){
if (betamount > balance) {
return false;
} else {
return true;
}
}


public void showbalance (){
NumberFormat nf = NumberFormat.getCurrencyInstance();
System.out.println("Available balance is : " + nf.format(balance));
}
}


Main class

import java.util.Random;
import java.util.Scanner;

public class BettingGame {

static Random myRandom = new Random();
static Scanner myScanner = new Scanner(System.in);

publi
c static void main(String[] args) {

Account myAccount = new Account(1000);
int available;
myAccount.showbalance();
boolean keepgoiang = true;

do {

System.out.println ("How much will you bet? ");
if (!myScanner.hasNextInt()){
myScanner.next();
continue;
}
int bet = myScanner.nextInt();
if (bet == 0) {
break;
}
if
(myAccount.checkBet(bet)){

do {
System.out.println ("Which number do you chose");
if (myScanner.hasNextInt()){
break;
}
}while (!myScanner.hasNextInt());
int number = myScanner.nextInt();
int ra
nnum = RandomGenerator(0,10);
System.out.println("Lucky number is: " + rannum);
if (number == rannum){
System.out.print("You win. ");
myAccount.credit(bet);
} else {
System.out.print("Better Luck next time. ");
myAccount.debit(bet);
}


} else {
System.out.println ("Not enough founds for that bet");
}
myAccount.showbalance();
if (Account.balance == 0) {
keepgoing = false;
}

}while (keepgoing);

if (myAccount.balance > 0 ) {
System.out.println("Great you quit with money on your pocket");
myAccount.showbalance();
} else {
System.out.println("You are fucked!");
myAccount.showbalance();
}


}

public static int RandomGenerator (int min, int max){
int RamNumber = myRandom.nextInt(10) + 1;
return RamNumber;
}


}


An image of the output on the console:

No comments: