Tuesday, August 7, 2007

code:Loan Amortization

This is a very useful loan amortization program. You will be asked to enter loan amount, number of years to pay of the loan, and annual interest rate. Once the input is entered the program will show you month by month interest, principal and balance.

This code is not java application but rather a java applet that can run in a web browser. Main difference between a java application and a java applet is that an applet does NOT have a main method that all java applications must have.

NOTE: I would like to thank all from the comp . lang . java . programmer goggle group that helped out with the amortization schedule formulas and the math part of the program as I am not that good in math :)


/**
* Author: http://javacodee.blogspot.com/
* Date: Aug 7, 2007
* Time: 7:59:28 PM
*/

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
import java.lang.*;

public class LoanSchedule extends JApplet implements ActionListener
{
//Create all needed labels
private JLabel jlblLoanAmount = new JLabel("Loan Amount");
private JLabel jlblNumOfYears = new JLabel("Number Of Years");
private JLabel jlblInterestRate = new JLabel("Interest Rate (Annual)");

//Create all needed text fields
private JTextField jtfLoanAmount = new JTextField(10);
private JTextField jtfNumOfYears = new JTextField(10);
private JTextField jtfInterestRate = new JTextField(10);

//Calculate button is also needed
private JButton jbtCalculate = new JButton("Amortize Loan");

//...and a text area where the results will be displayed
private JTextArea jtaResults = new JTextArea();

public void init()
{
//Panel p1 will hold the input
JPanel p1 = new JPanel();
p1.setLayout(new GridLayout(3,2));
p1.add(jlblLoanAmount);
p1.add(jtfLoanAmount);
p1.add(jlblNumOfYears);
p1.add(jtfNumOfYears);
p1.add(jlblInterestRate);
p1.add(jtfInterestRate);

//Panel p2 will hold panel p1 and the calculate button
JPanel p2 = new JPanel();
p2.setLayout(new BorderLayout());
p2.setBorder(new TitledBorder("Enter loan amount, Number of years and annual interest rate"));
p2.add(p1, BorderLayout.WEST);
p2.add(jbtCalculate, BorderLayout.EAST);

//Action listener for the button
jbtCalculate.addActionListener(this);

//Make the text area scrollable and uneditable
JScrollPane scrollPane = new JScrollPane(jtaResults);
jtaResults.setRows(12);
jtaResults.setEditable(false);

//Place the two panels to the applet
getContentPane().add(p2, BorderLayout.CENTER);
getContentPane().add(scrollPane, BorderLayout.SOUTH);
}

public void actionPerformed(ActionEvent e)
{
if(e.getSource() == jbtCalculate)
calculateLoan();
else
System.out.println("you will never see this text!");
/*
Because we only have one element that uses actionListener (jbtCalculate) this method should only have
a call to calculate() method in it but i put the if-else statement just to show that it can handle other
elements with alctiolistener. For example, if we had another button that had addActionListener attached to it
we could say something like this:

if(e.getSource() == jbtCalculate)
{
do something here;
}
else if(e.getSource() == jbtSomeOtherElement)
{
do something else here;
}
*/
}

public void calculateLoan()
{
int numberOfYears = Integer.parseInt(jtfNumOfYears.getText());
double loanAmount = Double.parseDouble(jtfLoanAmount.getText());
double annualInterestRate = (Double.parseDouble(jtfInterestRate.getText())) / 100;

double monthlyInterestRate = annualInterestRate / 12;
double numberOfMonths = numberOfYears * 12;
double monthlyPayment = loanAmount * (monthlyInterestRate / (1 - Math.pow(1 + monthlyInterestRate, - numberOfMonths)));
double totalPayment = monthlyPayment * numberOfMonths;
double balance = loanAmount;
double interest;
double principal;

jtaResults.append("Payment#\t" + "Interest\t" + "Principal\t" + "Balance\n\n");

for(int i = 0; i < numberOfYears * 12; i++)
{
interest = (int)(monthlyInterestRate * balance * 100) / 100.0;
principal = (int)((monthlyPayment - interest) * 100 ) / 100.0;
balance = (int)((balance - principal) * 100 ) / 100.0;

jtaResults.append(i + 1 + "\t" + interest + "\t" + principal + "\t" + balance +"\n");
}

jtaResults.append("\n\nMonthly Payment: $" + (int)(monthlyPayment * 100) / 100.0 + "\n");
jtaResults.append("Total Payment: $" + (int)(totalPayment * 100) / 100.0 + "\n\n");
}

}

Monday, August 6, 2007

Different IDEs

There are so many different IDEs to chose from these days. Ever since I started coding I have been using TextPad since our professor told us that would be the best way to learn Java since it doesn't show you any IntelliSense thus making you really thing about what you're doing. But just recently (last month) i started looking at different IDEs or Integrated Development Environments. Right now I'm using IntelliJIDEA 6.0 and it's great and it has so many useful tools and functios, to bad that it's trial software and I'll have to pay for it in less then a month in order to use it...

I'm just not sure if it is worth it (I think the price is around $100, and around $300 for a better version). I would like to hear from people that are using it, what they think about it and if it has any major problems and/or bugs.

I also used NetBeans but for some reason i like IDEA more but will probably switch back to NetBeans once the trial on IDEA expires (unless i get some good feedback on it :) ).

I heard about some other IDEs too, such as Eclipse and JCreator but i never got to use them...for now...

So for now I'll stick with IDEA until my subscription expires (Aug 31, I believe) and after that who knows... any suggestions are welcome.



~DR.

Saturday, August 4, 2007

code: Zero Division

***Exception Handling***

This first program is a simple one that shows what happens when you divide by zero or if you enter a letter instead of a number when you try to divide two numbers. The first sample does not have any type of exception handling... When you try and run this program make sure that you enter a zero for the second number so that you get the exception shown (you can also enter a letter when it's asking you for a number and you will get a inputMismatchException). As you can see it can get really messy and unprofessional.

/**
* Author: http://javacodee.blogspot.com/
* Date: Aug 5, 2007
* Time: 12:49:42 AM
*/
import java.util.Scanner;

public class DivisionByZeroNoExceptionHandling
{
public static void main(String args[])
{
Scanner input =new Scanner(System.in);
int topNumber =0;
int bottomNumber =0;

System.out.print("Enter the first number: ");
topNumber =input.nextInt();
System.out.print("Enter the second number: ");
bottomNumber =input.nextInt();

System.out.println("\n****************************\nRESULT:\n" +topNumber +" divided by " +bottomNumber
+" equals " +result(topNumber, bottomNumber) +"\n****************************");
}

public static int result(int numerator, int denominator)
{
return numerator /denominator;
}
}

This next code sample will be using exception handling and you should be able to see the difference it makes just make sure you enter wrong input just like in the first example. Enter a zero for the second number and/or enter a letter for any of the numbers.

Exception handling is useful because it removes the error-handling code from the program and it improves clarity of the program. When you write a exception-prone program you can decide to handle any or all exceptions or all exceptions of a certain type.

/**
* Author: http://javacodee.blogspot.com/
* Date: Aug 4, 2007
* Time: 11:02:04 AM
*/
import java.util.Scanner;
import java.util.InputMismatchException;

public class DivisionByZero
{
public static void main(String args[])
{
Scanner input =new Scanner(System.in);
int topNumber =0;
int bottomNumber =0;
boolean loopAgain =true;

do
{
try
{
System.out.print("Enter the first number: ");
topNumber =input.nextInt();
System.out.print("Enter the second number: ");
bottomNumber =input.nextInt();

System.out.println("\n****************************" +
"\nRESULT:\n" +topNumber +" divided by " +bottomNumber +" equals " +
result(topNumber, bottomNumber) +"\n****************************");
loopAgain =false;
}
catch(ArithmeticException arithmeticEx)
{
System.out.println("\n***Exception***\n***Zero is invalid denominator***\n");
}
catch (InputMismatchException inputMismatchEx)
{
System.out.println("\n***Exception***\n***Please enter numbers only***\n");
input.nextLine();
}
}
while(loopAgain);
}

public static int result(int numerator, int denominator)
{
return numerator /denominator;
}
}

Friday, August 3, 2007

code: Number Guessing

***Simple GUI Based I/O***

I created this code to show how some basic Java GUI (graphical user interface) components work and how to use them in a program. GUI programs can get complicated and hard to code very quickly because there are so many parts to GUI programming in Java... This program will only use some simple GUI-based input/output with JOptionPane. In future, i will probably post code that goes a little bit more in-depth when it comes to Java GUI.

/**
* Author: http://javacodee.blogspot.com/
* Date: Aug 3, 2007
* Time: 11:08:31 PM
*/
import javax.swing.*;
import java.util.Random;

public class GuessNum
{
public static void main(String args[])
{
String guess =null;
int num =0;
int randomNumber =0;
int playAgain =0;
int counter =0;
Random generator = new Random();

do
{
randomNumber =generator.nextInt(100);

guess = JOptionPane.showInputDialog("I'm thinking of a number between 1 and 100...\nwhat is your guess?");
num =Integer.parseInt(guess);

/*
Since JOptionPane returns a String you have to use Integer.parseInt(guess) to convert the string to a new int value.
The 'Integer' class wraps a value of the primitive type 'int' in an object. If you need to assign the string to a double for example you would use Double.parseDouble(guess), another one you could use is Float.parseFloat(guess) if you need a float value. For all of the different methods and constructors please review the java documentation and look under java.lang.Object.
*/

while(num !=randomNumber)
{
if(num >randomNumber)
{
JOptionPane.showMessageDialog(null, "Nope, that's not it! Your number is too high\nTry again...",
"Guess Incorrect!", JOptionPane.INFORMATION_MESSAGE);

/*
The first string
"Nope, that's not it! Your number is too high\nTry again..." represents the text that will show up in the message dialog window and the second string "Guess Incorrect!" represents the text that will show up as the windows title located in the top part of the window.
*/

}
else
{
JOptionPane.showMessageDialog(null, "Nope, that's not it! Your number is too low\nTry again...",
"Guess Incorrect!", JOptionPane.INFORMATION_MESSAGE);
}

guess =JOptionPane.showInputDialog("I'm thinking of a number between 1 and 100...\nwhat is your guess?");
num =Integer.parseInt(guess);
counter++;

/*
Variable 'counter' will keep tract of the number of tries that took you to get the number guessed right
*/

}

playAgain =JOptionPane.showConfirmDialog(null, "After "+counter+" tries you got it!\nDo you want to play again?",
"Play again?", JOptionPane.YES_NO_OPTION);
}
while(playAgain != JOptionPane.NO_OPTION);

JOptionPane.showMessageDialog(null, "Thank you for playing!", "Goodbye", JOptionPane.INFORMATION_MESSAGE);
}
}

Thursday, August 2, 2007

code: ATM Machine

This is a very simple code that i wrote. It's just an ATM machine and it's very simple... it uses some "if then" and "switch" statements and it's a good practice for a beginner coder.

If you have any question and/or comments please let me know because I'm fairly new to Java myself so any hints and tricks are welcome :)


/**
* Author: http://javacodee.blogspot.com/
* Date: Aug 1, 2007
* Time: 11:30:18 PM
*/
import java.util.Scanner;

public class AtmMachine
{
private double availableBal =80;
private double totalBal =100;
Scanner input = new Scanner(System.in);

public int userAccount()
{
System.out.print("Enter your account number: ");
int account;
account = input.nextInt();

return account;
}

public int userPin()
{
System.out.print("Enter your pin number: ");
int pin;
pin =input.nextInt();

return pin;
}

public void startAtm()
{
userAccount();
userPin();
drawMainMenu();
}

public void drawMainMenu()
{
int selection;

System.out.println("\nATM main menu:");
System.out.println("1 - View account balance");
System.out.println("2 - Withdraw funds");
System.out.println("3 - Add funds");
System.out.println("4 - Terminate transaction");
System.out.print("Choice: ");
selection =input.nextInt();

switch(selection)
{
case 1:
viewAccountInfo();
break;
case 2:
withdraw();
break;
case 3:
addFunds();
break;
case 4:
System.out.println("Thank you for using this ATM!!! goodbye");
}
}

public void viewAccountInfo()
{
System.out.println("Account Information:");
System.out.println("\t--Total balance: $"+totalBal);
System.out.println("\t--Available balance: $"+availableBal);
drawMainMenu();
}

public void deposit(int depAmount)
{
System.out.println("\n***Please insert your money now...***");
totalBal =totalBal +depAmount;
availableBal =availableBal +depAmount;
}

public void checkNsf(int withdrawAmount)
{
if(totalBal -withdrawAmount < 0)
System.out.println("\n***ERROR!!! Insufficient funds in you accout***");
else
{
totalBal =totalBal -withdrawAmount;
availableBal =availableBal -withdrawAmount;
System.out.println("\n***Please take your money now...***");
}
}

public void addFunds()
{
int addSelection;

System.out.println("Deposit funds:");
System.out.println("1 - $20");
System.out.println("2 - $40");
System.out.println("3 - $60");
System.out.println("4 - $100");
System.out.println("5 - Back to main menu");
System.out.print("Choice: ");
addSelection =input.nextInt();

switch(addSelection)
{
case 1:
deposit(20);
drawMainMenu();
break;
case 2:
deposit(40);
drawMainMenu();
break;
case 3:
deposit(60);
drawMainMenu();
break;
case 4:
deposit(100);
drawMainMenu();
break;
case 5:
drawMainMenu();
break;
}
}

public void withdraw()
{
int withdrawSelection;

System.out.println("Withdraw money:");
System.out.println("1 - $20");
System.out.println("2 - $40");
System.out.println("3 - $60");
System.out.println("4 - $100");
System.out.println("5 - Back to main menu");
System.out.print("Choice: ");
withdrawSelection =input.nextInt();

switch(withdrawSelection)
{
case 1:
checkNsf(20);
drawMainMenu();
break;
case 2:
checkNsf(40);
drawMainMenu();
break;
case 3:
checkNsf(60);
drawMainMenu();
break;
case 4:
checkNsf(100);
drawMainMenu();
break;
case 5:
drawMainMenu();
break;
}
}

public static void main(String args[])
{
AtmMachine myAtm = new AtmMachine();
myAtm.startAtm();
}
}

New to blogger

I just joined blogger and i hope it will be a fun experience... I'm still not sure how everything works and i don't really know how to get it touch with other java programmers out there on blogger so i hope that you will get in touch with me to comment on my code and how can i improve it and of course i will comment back too...

Every now and then i will post some of my Java code and share it with the world... And please if you want to use some (or whole) of my samples let me know don't just copy and paste and then turn it in as your because that's stealing and stealing is not good :) I don't have anything agenst anyone that wants to use my samples but i would just like to know who and why is it being used that's all.

happy coding everyone!

*****I would like to know if anyone can tell me if there is a way in blogger to fix your posts so that it doesn't mess up my curly bracket alignment and code formating because that really annoys me and it makes the code really hard to understand...

thanks in advance!*****