2

これは、宿題の一環として取り組んでいる Java プログラム用です。私は自分のために仕事をしたくありませんが、立ち往生しています。私は Java の初心者で、NetBeans IDE 7.0.1 を使用しています。

ユーザー入力を検証しようとすると、いくつかの例外処理に問題があります。このプログラムは、ユーザー入力からの慈善寄付を記録します。ただし、寄付金額のテキスト フィールドの入力を検証できませんでした。ユーザーが数字の代わりにテキストを入力した場合、入力が無効であることを通知し、例外処理でエラーを処理して、ユーザーが入力を修正した後に続行するようにしたいと考えています。どんな助けでも大歓迎です。

これが私のコードです:

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();
}

}

これが私の修正されたコードです。いくつかのユーザー入力テストの後、100、40 などの全額ではなく、100.00、40.00 などを使用すると例外が発生します。何か考えはありますか?

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();
}

}

4

3 に答える 3

2

ここInputVerifierで説明したを使用できます。

于 2012-05-25T07:03:22.953 に答える
1
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++;
        } 
    }
}
于 2012-05-25T07:30:30.847 に答える
0

このようなものがうまくいくでしょう。これにより、金額が空ではなく、既存の方法に基づいて数字のみが含まれていることが確認されます。

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;

金額が 0 でないことを確認したい場合は、金額を int に解析し、parsedAmount<0. NPE および numberformatexception を回避するために、金額が空ではなく、数字 (ei last:) のみであることが確認された後に、これを行う必要があります。

于 2012-05-25T07:18:22.740 に答える