+ Reply to Thread
Results 1 to 4 of 4

Thread: Help for Exception in thread "main" java.lang.NullPointerException

  1. #1
    Junior Member
    Join Date
    Jan 2007
    Posts
    14
    Rep Power
    7

    Help for Exception in thread "main" java.lang.NullPointerException

    Hi All,
    I am doing a banking application using MVC architecture. Everything was working fine before i add an interface and Long termaccount class. I need to fulfill one requiremnt that I need to create an LongTerm Account which must not allow any withdrawls and I created a class for LongTermAccount which extends Account Type(abstract class and was containing withdraw abstract method) to know which account is selected. To fulfill the requirement i created another interface which has withdraw method and then this Account Type class(now the abstract method is made as concrete class) implements that interface. When I tried to compile the application i am getting the following message:

    Exception in thread "main" java.lang.NullPointerException
    at view.LoanAndAccountHandler.isSubclassOf(LoanAndAccountHandler.java:323)
    at view.LoanAndAccountHandler.isSubclassOf(LoanAndAccountHandler.java:326)
    at view.LoanAndAccountHandler.getSubclasses(LoanAndAccountHandler.java:307)
    at view.LoanAndAccountHandler.initAccountPanel(LoanAndAccountHandler.java:139)
    at view.LoanAndAccountHandler.(LoanAndAccountHandler.java:86)
    at view.LoanAndAccountHandler.main(LoanAndAccountHandler.java:367)

    Could somebody helps me. I am also posting all of my classes also. Someone can ask me why I am using this MVC since my professor has given me half code and asked to fulfill the requirements so i must have to do in that way.


    // Withdraw interface
    package model.accounts;

    public interface Withdraw {

    public float withdraw(float amount);
    }


    //Account Type abstract Class

    package model.accounts;

    public abstract class AccountType implements Withdraw{

    private float amount = 0;

    public float getAmount() {
    return amount;
    }

    protected void setAmount(float amount) {
    this.amount = amount;
    }

    public void deposit(float amount) {
    float current = this.getAmount();
    this.setAmount(current + amount);
    }

    public float withdraw(float amount){
    return amount;
    }
    }

    // Long Term Account

    package model.accounts;

    public class LongTermAccount extends AccountType{

    public String toString()
    {
    return "LoanTerm Account";
    }
    }


    // Savings Account class( just for reference, other account class)
    package model.accounts;

    public class SavingsAccount extends AccountType{

    public float withdraw(float amount) {
    float current = this.getAmount();
    float withdrawal;

    if(current - amount >= 0)
    withdrawal = amount;
    else
    withdrawal = current;

    this.setAmount(current - withdrawal);
    return withdrawal;
    }

    public String toString()
    {
    return "Sav. Account";
    }


    }

    //LoanAndAccountHandler class(main class)

    package view;

    import java.awt.Dimension;
    import java.awt.FlowLayout;
    import java.awt.GridLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.io.File;
    import java.io.FilenameFilter;
    import java.util.ArrayList;

    import javax.swing.BorderFactory;
    import javax.swing.DefaultListModel;
    import javax.swing.JButton;
    import javax.swing.JComboBox;
    import javax.swing.JFrame;
    import javax.swing.JList;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTextField;
    import javax.swing.ListSelectionModel;
    import javax.swing.WindowConstants;
    import javax.swing.event.ListSelectionEvent;
    import javax.swing.event.ListSelectionListener;

    import model.Account;
    import model.AccountList;
    import model.accounts.AccountType;
    import model.accounts.Withdraw;
    import model.handler.*;
    import mvc.Model;
    import mvc.View;


    @SuppressWarnings("serial")
    public class LoanAndAccountHandler extends JFrame implements View, ListSelectionListener{

    private AccountList model;
    private ArrayList accountTypes;
    private ArrayList loanTypes;
    private DefaultListModel listModel;
    private JList list;

    private JTextField nameField;
    private JButton createButton;
    private JComboBox typeSelector;
    private JComboBox loanSelector;

    private JTextField amountField;

    private JButton depositButton, withdrawButton;

    private JTextField loanField;
    private JButton requestButton;


    public LoanAndAccountHandler() {
    super();

    this.setTitle("Loan- and Account-Handler");

    this.setSize(700, 500);

    model = new AccountList();
    model.addView(this);

    // Initialize list

    listModel = new DefaultListModel();
    list = new JList(listModel);
    list.addListSelectionListener(this);

    list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    list.setLayoutOrientation(JList.VERTICAL);
    list.setVisibleRowCount(-1);

    JScrollPane listPane = new JScrollPane(list, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
    JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
    listPane.setPreferredSize(new Dimension(1, 1));


    // Initialize controls

    JPanel controlPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));

    JPanel accountPanel = this.initAccountPanel();
    controlPanel.add(accountPanel);

    JPanel transactionPanel = this.initTransactionPanel();
    controlPanel.add(transactionPanel);

    JPanel loanPanel = this.initLoanPanel();
    controlPanel.add(loanPanel);

    // Place the elements

    JPanel selectionPanel = new JPanel();
    selectionPanel.setLayout(new GridLayout(1,2));
    selectionPanel.add(listPane);

    JPanel contentPane = new JPanel();
    contentPane.setLayout(new GridLayout(1,2));
    contentPane.add(listPane);
    contentPane.add(controlPanel);

    setContentPane(contentPane);

    this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    this.setResizable(false);

    }

    private JPanel initAccountPanel(){

    class CreateActionListener implements ActionListener{

    public void actionPerformed(ActionEvent event) {
    String name = nameField.getText();
    if(name.length() == 0)
    return;

    if(typeSelector.getSelectedIndex() == 0)
    return;

    Class cl = accountTypes.get(typeSelector.getSelectedIndex() - 1);
    try {
    AccountType newType = (AccountType)cl.newInstance();
    Account account = new Account(name, newType);
    model.addAccount(account);
    listModel.addElement(account);
    } catch (InstantiationException e) {
    e.printStackTrace();
    } catch (IllegalAccessException e) {
    e.printStackTrace();
    }
    }
    }

    accountTypes = getSubclasses("model/accounts", "model.accounts.", AccountType.class);

    JPanel accountPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
    accountPanel.setPreferredSize(new Dimension (335, 100));
    accountPanel.setBorder(BorderFactory.createTitledBorder("Create Account"));

    nameField = new JTextField(15);
    accountPanel.add(nameField);

    Object[] typeSelection = new Object[accountTypes.size() + 1];
    typeSelection[0] = "Account Types";
    for(int i = 0; i < accountTypes.size(); i++){
    Class cl = accountTypes.get(i);
    try {
    typeSelection[i+1] = cl.newInstance();
    } catch (InstantiationException e) {
    e.printStackTrace();
    } catch (IllegalAccessException e) {
    e.printStackTrace();
    }
    }
    typeSelector = new JComboBox(typeSelection);
    accountPanel.add(typeSelector);

    createButton = new JButton("Create");
    createButton.addActionListener(new CreateActionListener());
    accountPanel.add(createButton);

    return accountPanel;
    }

    private JPanel initTransactionPanel(){

    class TransactionActionListener implements ActionListener{

    private boolean deposit;

    public TransactionActionListener(boolean deposit) {
    super();
    this.deposit = deposit;
    }

    public void actionPerformed(ActionEvent event) {
    int index = list.getSelectedIndex();
    if(index == -1)
    return;

    Account account = (Account)listModel.get(index);
    float amount;
    try{
    amount = Float.parseFloat(amountField.getText());
    } catch (Exception e) {
    return;
    }

    if(deposit)
    account.deposit(amount);
    else
    account.withdraw(amount);
    list.repaint();
    }


    }

    JPanel transactionPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
    transactionPanel.setPreferredSize(new Dimension (335, 100));
    transactionPanel.setBorder(BorderFactory.createTitledBorder("Do Transaction"));
    amountField = new JTextField(15);
    transactionPanel.add(amountField);

    depositButton = new JButton("Deposit");
    depositButton.addActionListener(new TransactionActionListener(true));
    depositButton.setEnabled(false);
    transactionPanel.add(depositButton);

    withdrawButton = new JButton("Withdraw");
    withdrawButton.addActionListener(new TransactionActionListener(false));
    withdrawButton.setEnabled(false);
    transactionPanel.add(withdrawButton);
    return transactionPanel;
    }

    private JPanel initLoanPanel(){

    class ValidateActionListener implements ActionListener{

    public void actionPerformed(ActionEvent event) {
    int index = list.getSelectedIndex();
    if(index == -1)
    return;

    Account account = (Account)listModel.get(index);

    PersonalLoanValidator validator = new PersonalLoanValidator();
    CompanyLoanValidator cvalidator = new CompanyLoanValidator();
    ShortTermLoanValidator svalidator= new ShortTermLoanValidator();

    String answer = account.approveLoan(validator);


    answer = account.approveLoan(cvalidator);
    answer = account.approveLoan(svalidator);
    loanField.setText(answer);

    // loanField.setText(ans);
    }
    }

    loanTypes = getSubclasses("model/handler", "model.handler.",LoanType.class);

    JPanel loanPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
    loanPanel.setPreferredSize(new Dimension (335, 100));
    loanPanel.setBorder(BorderFactory.createTitledBorder("Request Loan"));

    loanField = new JTextField(15);
    loanPanel.add(loanField);
    loanField.setEditable(false);

    Object[] loanSelection = new Object[loanTypes.size()+1];
    loanSelection[0]= "Loan Types";

    for(int i=0;i {
    Class c2 = loanTypes.get(i);
    try {
    loanSelection[i+1] = c2.newInstance();
    } catch (InstantiationException e) {
    e.printStackTrace();
    } catch (IllegalAccessException e) {
    e.printStackTrace();
    }
    }

    loanSelector = new JComboBox(loanSelection);
    loanPanel.add(loanSelector);

    requestButton = new JButton("Request");
    requestButton.addActionListener(new ValidateActionListener());
    requestButton.setEnabled(false);
    loanPanel.add(requestButton);

    return loanPanel;
    }


    private ArrayList getSubclasses(String searchPath, String classPath, Class superclass){
    final String classExt = ".class";

    ArrayList classes = new ArrayList();

    File dir = new File(searchPath);
    FilenameFilter filter = new FilenameFilter() {
    public boolean accept(File dir, String name) {
    return name.endsWith(classExt);
    }
    };

    String[] children = dir.list(filter);
    if (children == null){
    System.out.println(searchPath + " does not exist or is not a directory");
    return classes;
    }

    for (int i = 0; i < children.length; i++) {
    // Get filename of file or directory
    String filename = children[i];
    String classname = filename.substring(0, filename.length() - classExt.length());
    try {
    Class cl = Class.forName(classPath + classname);
    if(isSubclassOf(cl, superclass))
    classes.add(cl);
    } catch (ClassNotFoundException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    }

    return classes;

    }

    private boolean isSubclassOf(Class subclass, Class superclass){
    if(subclass == java.lang.Object.class)
    return false;

    if(subclass.getSuperclass() == superclass)
    return true;

    return isSubclassOf(subclass.getSuperclass(), superclass);
    }



    public Model getModel() {
    return model;
    }

    public void update() {
    // TODO Auto-generated method stub

    }

    public void update(int aspect) {
    // TODO Auto-generated method stub

    }

    public void update(int aspect, Object object) {
    // TODO Auto-generated method stub

    }


    public void valueChanged(ListSelectionEvent arg0) {
    int index = list.getSelectedIndex();
    loanField.setText("");
    if(index == -1){
    depositButton.setEnabled(false);
    withdrawButton.setEnabled(false);
    requestButton.setEnabled(false);
    } else {
    depositButton.setEnabled(true);
    withdrawButton.setEnabled(true);
    requestButton.setEnabled(true);
    }
    }

    public static void main(String[] args)throws Exception{
    JFrame.setDefaultLookAndFeelDecorated(true); //Java-Representation
    LoanAndAccountHandler handler = new LoanAndAccountHandler();
    handler.setVisible(true);
    handler.setLocationRelativeTo(null);

    }

    }


    Where did i make mistake could anyone please tell me.

  2. #2
    Moderator t_mohan's Avatar
    Join Date
    Apr 2006
    Location
    India
    Posts
    578
    Rep Power
    23

    Re: Help for Exception in thread "main" java.lang.NullPointerException

    Hi ,

    Can u tel me ur name, i couldnot understand ur name. Is it Arumahi

    Ok, the method isSubClassOf is throwing the null pointer exception

    private boolean isSubclassOf(Class subclass, Class superclass){
    System.out.println("1");
    if(subclass == java.lang.Object.class)
    return false;
    System.out.println("2");
    if(subclass.getSuperclass() == superclass)
    return true;
    System.out.println("3");
    boolean xxx = isSubclassOf(subclass.getSuperclass(), superclass);
    System.out.println("4");
    return xxx;
    }

    your subclass object is null and ur trying to get the superclass of the subclass object, since the subclass object is null, you are getting a null pointer exception. If u want some confirmation keep some debug statement like the one i specified above , i modified it because the last statement of the the returning function should be "return"

    Let me know your questions

    Thank You
    Last edited by t_mohan; 09-04-07 at 04:46 PM.

  3. #3
    Junior Member
    Join Date
    Jan 2007
    Posts
    14
    Rep Power
    7

    Re: Help for Exception in thread "main" java.lang.NullPointerException

    Hi Mohan,

    I am Aruna,Thanks for the reply and i tried as you suggested I found that Longterm account is not extending Account Type class but I couldn't solve that problem Could you please clearly tell me. What i have to do.


    Best Regards,
    Aruna

  4. #4
    Member avadhoot.dharmadhikari's Avatar
    Join Date
    Aug 2006
    Location
    Parli-V
    Age
    29
    Posts
    60
    Rep Power
    9

    Re: Help for Exception in thread "main" java.lang.NullPointerException

    Read this artical carefully. i hope after reading you solve your proble.otherwise give me full code i can check and send it you.


    1. Null pointers!

    Null pointers are one of the most common errors that Java programmers make. Compilers can't check this one for you - it will only surface at runtime, and if you don't discover it, your users certainly will.
    When an attempt to access an object is made, and the reference to that object is null, a NullPointerException will be thrown. The cause of null pointers can be varied, but generally it means that either you haven't initialized an object, or you haven't checked the return value of a function.
    Many functions return null to indicate an error condition - but unless you check your return values, you'll never know what's happening. Since the cause is an error condition, normal testing may not pick it up - which means that your users will end up discovering the problem for you. If the API function indicates that null may be returned, be sure to check this before using the object reference!
    Another cause is where your initialization has been sloppy, or where it is conditional. For example, examine the following code, and see if you can spot the problem.

    public static void main(String args[]){ // Accept up to 3 parameters String[] list = new String[3]; int index = 0; while ( (index < args.length) && ( index < 3 ) ) { list[index++] = args[index]; } // Check all the parameters for (int i = 0; i < list.length; i++) { if (list[i].equals "-help") { // ......... } else if (list[i].equals "-cp") { // ......... } // else ..... } }This code (while a contrived example), shows a common mistake. Under some circumstances, where the user enters three or more parameters, the code will run fine. If no parameters are entered, you'll get a NullPointerException at runtime. Sometimes your variables (the array of strings) will be initialized, and other times they won't. One easy solution is to check BEFORE you attempt to access a variable in an array that it is not equal to null.

+ Reply to Thread

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Similar Threads

  1. Replies: 1
    Last Post: 07-02-07, 01:41 PM
  2. Replies: 1
    Last Post: 30-01-07, 06:21 PM
  3. J2EE - Can u kill thread manually
    By preethisingh in forum Java Interview / Technical Questions
    Replies: 0
    Last Post: 23-01-07, 03:59 PM
  4. J2EE - various ways of creating a thread
    By preethisingh in forum Java Interview / Technical Questions
    Replies: 0
    Last Post: 23-01-07, 03:58 PM
  5. Daemon Thread
    By anitha.s in forum JAVA Technologies
    Replies: 3
    Last Post: 13-12-06, 12:54 PM

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts

Content Relevant URLs by vBSEO 3.5.1 PL1