2

This is for a Java program I'm working on as part of a homework assignment. I don't want the work done for me, but I'm stuck. I'm fairly new to Java, and using NetBeans IDE 7.0.1.

I'm having difficulty with some exception handling when trying to validate user input. This program will log charitable donations from user input. However, I've not been successful in validating the donation amount text field input. If a user inputs text instead of numbers, I would like them to be notified that their input was invalid, and I'd like the exception handling to handle the error and carry on after the user fixes their entry. Any help is greatly appreciated.

Here is my code:

package donorgui;


import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import java.io.*;
import java.awt.*;

public class DonorGUI extends JFrame
{

// Components
private JPanel panel;
private JTextArea results;
private JButton entryButton;
private JButton exitButton;
private JButton clearButton;
private JTextField donorField;
private JTextField charityField;
private JTextField pledgeField;

//create variables
String[] donorName = new String[20];
String[] charityName = new String[20];
double[] donationAmt = new double[20];
int i = 0;


// Constants for the window size
private final int WINDOW_WIDTH = 750;
private final int WINDOW_HEIGHT = 510;

//Constructor
public DonorGUI(){

    // Set the title.
    setTitle("Donor");

    // Specify what happens when the close button is clicked.
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    // Build the panel that contains the other components.
    buildPanel();

    // Add the panel to the content pane.
    add(panel);

    // Size and display the window.
    setSize(WINDOW_WIDTH, WINDOW_HEIGHT);
    setVisible(true);
}

//The buildPanel method creates a panel containing other components.
private void buildPanel(){

    // Create labels to display instructions.
    JLabel message1 = new JLabel("Name of the Donor:");
    JLabel message2 = new JLabel("Name of the Charity:");
    JLabel message3 = new JLabel("Amount of the Pledge:");

    //instantiate the results area
    results = new JTextArea(25,60);

    // Create text fields to receive user input
    donorField = new JTextField(10);
    charityField = new JTextField(10);
    pledgeField = new JTextField(10);


    //create the user buttons to cause action
    entryButton = new JButton("Enter Donation.");
    entryButton.addActionListener(new EntryButtonListener());
    exitButton = new JButton("EXIT");
    exitButton.addActionListener(new ExitButtonListener());
    clearButton = new JButton ("Clear Fields");
    clearButton.addActionListener(new ClearButtonListener());


    // Create a panel.
    panel = new JPanel();

    //set the LayoutManager
    panel.setLayout(new FlowLayout());

    // Add the labels, text fields, and button to the panel.
    panel.add(message1);
    panel.add(donorField);
    panel.add(message2);
    panel.add(charityField);
    panel.add(message3);
    panel.add(pledgeField);
    panel.add(results);
    panel.add(entryButton);
    panel.add(exitButton);
    panel.add(clearButton);

}
private class EntryButtonListener implements ActionListener {

    public void actionPerformed(ActionEvent e) {

        donorName[i] = donorField.getText();
        charityName[i] = charityField.getText();
        donationAmt[i] = Double.parseDouble(pledgeField.getText());
        results.append(donorName[i]+" "+charityName[i]+" "+donationAmt[i]+"\n ");
        i++;
    } 
}
public boolean donationAmt(String amount) {
    int i = 0;
    try {
        i = Integer.parseInt (amount);
        return true;
    }
    catch (NumberFormatException e) {
        JOptionPane.showMessageDialog(null, "Invalid Input.  Please enter a dollar amount");
        return false;
    }


}
private class ClearButtonListener implements ActionListener {
    @Override
    public void actionPerformed (ActionEvent e) {
        donorField.setText("");
        charityField.setText("");
        pledgeField.setText("");
        }
}
private class ExitButtonListener implements ActionListener {

    public void actionPerformed(ActionEvent e) {
        System.exit(0);
    }
}

/* Application method */
public static void main(String[] args){

    DonorGUI rpc = new DonorGUI();
}

}

Here is my revised code. After some user input testing, I'm getting an exception when I use 100.00, 40.00, etc... instead of whole dollar amounts, such as 100, 40, etc. Any thoughts?

package donorgui;


import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import java.io.*;
import java.awt.*;

public class DonorGUI extends JFrame
{
// Components
private JPanel panel;
private JTextArea results;
private JButton entryButton;
private JButton exitButton;
private JButton clearButton;
private JTextField donorField;
private JTextField charityField;
private JTextField pledgeField;

//create variables
String[] donorName = new String[20];
String[] charityName = new String[20];
double[] donationAmt = new double[20];
int i = 0;


// Constants for the window size
private final int WINDOW_WIDTH = 750;
private final int WINDOW_HEIGHT = 550;

//Constructor
public DonorGUI(){

    // Set the title.
    setTitle("Donor");

    // Specify what happens when the close button is clicked.
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    // Build the panel that contains the other components.
    buildPanel();

    // Add the panel to the content pane.
    add(panel);

    // Size and display the window.
    setSize(WINDOW_WIDTH, WINDOW_HEIGHT);
    setVisible(true);
}

//The buildPanel method creates a panel containing other components.
private void buildPanel(){

    // Create labels to display instructions.
    JLabel message1 = new JLabel("Name of the Donor:");
    JLabel message2 = new JLabel("Name of the Charity:");
    JLabel message3 = new JLabel("Amount of the Pledge:");

    //instantiate the results area
    results = new JTextArea(25,60);


    // Create text fields to receive user input
    donorField = new JTextField(10);
    charityField = new JTextField(10);
    pledgeField = new JTextField(10);


    //create the user buttons to cause action
    entryButton = new JButton("Enter Donation.");
    entryButton.addActionListener(new EntryButtonListener());
    exitButton = new JButton("EXIT");
    exitButton.addActionListener(new ExitButtonListener());
    clearButton = new JButton ("Clear Fields");
    clearButton.addActionListener(new ClearButtonListener());


    // Create a panel.
    panel = new JPanel();

    //set the LayoutManager
    panel.setLayout(new FlowLayout());

    // Add the labels, text fields, and button to the panel.
    panel.add(message1);
    panel.add(donorField);
    panel.add(message2);
    panel.add(charityField);
    panel.add(message3);
    panel.add(pledgeField);
    panel.add(results);
    panel.add(entryButton);
    panel.add(exitButton);
    panel.add(clearButton);

}
private class EntryButtonListener implements ActionListener {

    public void actionPerformed(ActionEvent e) {

        donorName[i] = donorField.getText();
        charityName[i] = charityField.getText();
                if (donationAmt(pledgeField.getText())) {
                    donationAmt[i] = Double.parseDouble(pledgeField.getText());
                }
        results.append(donorName[i]+" "+charityName[i]+" "+donationAmt[i]+"\n ");
        i++;
    } 
}

public boolean donationAmt(String amount) {
   if(amount==null || amount=="" || amount.length()<1){  //checking for empty field
        JOptionPane.showMessageDialog(null, "Please enter a dollar amount");
        return false;
    }

    for(int i = 0; i < amount.length(); i++){  //verifying dollar amount entered as number
            if (!Character.isDigit(amount.charAt(i))){ 
                JOptionPane.showMessageDialog(null, "Invalid input.  Please enter a dollar amount");
                return false;
            } 
    }
    return true;

}



private class ClearButtonListener implements ActionListener {
    @Override
    public void actionPerformed (ActionEvent e) {
        donorField.setText("");
        charityField.setText("");
        pledgeField.setText("");
        }
}
private class ExitButtonListener implements ActionListener {

    public void actionPerformed(ActionEvent e) {
        System.exit(0);
    }
}

/* Application method */
public static void main(String[] args){

    DonorGUI rpc = new DonorGUI();
}

}

1
  • 1
    Are you able to use a JSpinner for the amount? It would be easier for the user (& you). Commented May 25, 2012 at 7:08

3 Answers 3

2

You can use InputVerifier, discussed here.

Sign up to request clarification or add additional context in comments.

Comments

0

Something like this would work. This checks so that the amount is not empty and contains only digits based on your exisiting method.

public boolean donationAmt(String amount) {
       if(amount==null || amount=="" || amount.length()<1){  //check so that the amount field is not empty, pherhaps you can add a check so the amound is not 0 :)
            JOptionPane.showMessageDialog(null, "Invalid Input. The amount cannot be empty");
            return false;
        }

        for(int i = 0; i < amount.length(); i++){  //loop thru the string and check so that each char is a digit
                if (!Character.isDigit(amount.charAt(i))){ 
                    JOptionPane.showMessageDialog(null, "The amount can contain only numbers");
                    return false;
                } 
return true;

If you want to make sure that the amount is not 0, one approach would be to parse amount to int, and check so that parsedAmount<0. This should be done after it's verified that the amount is not empty and is only digits (e.i last:) ) to avoid NPE's and numberformatexception

Comments

0
private class EntryButtonListener implements ActionListener {

    public void actionPerformed(ActionEvent e) {

        donorName[i] = donorField.getText();
        charityName[i] = charityField.getText();
        if(donationAmt(pledgeField.getText())){
            donationAmt[i] = Double.parseDouble(pledgeField.getText());
            results.append(donorName[i] + " " + charityName[i] + " " + donationAmt[i] + "\n ");
            i++;
        } 
    }
}

1 Comment

Many thanks for the input folks. It seems that it's working from what I can tell. However, I'm having a new issue when I did some user input testing. If I input whole dollar amounts it works, but if I enter 10.00, 100.00, etc... it does not seem to validate. Any thoughts?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.