Лучшие способы обработки ввода нечисловых символов - PullRequest
0 голосов
/ 18 октября 2018

В настоящее время работает над небольшим проектом Java / Swing на основе графического интерфейса, который включает преобразование значений из одного измерения в другое.Я довольно новичок в Swing тоже.

Я отслеживаю, сколько конверсий («calcCount») сделал пользователь, однако счетчик также увеличивается, когда пользователь вводит нечисловой символ, независимо от того, генерируется ли исключение NumberFormatException - яустановка calcCount на ноль каждый раз, когда преобразование не выполняется в try / Catch, так что не должно происходить?(ниже).

try {
conversionFieldValue = Double.parseDouble(text);
} catch (NumberFormatException e) {
  calcCount = 0;
  JOptionPane.showMessageDialog(null, "Error: the value entered may not be a valid number. \nPlease ensure that you are entering a valid double, with or without a decimal place.", "Conversion error", JOptionPane.ERROR_MESSAGE);
  conversionCountLabel.setText("Conversion Count: " + calcCount);
}

В настоящее время единственное место, где увеличивается calcCount, находится в слушателе для convertButton, который срабатывает только в том случае, если введенное значение не пустое / нулевое и если источником является convertButton.Обработка кода выглядит следующим образом.

if(e.getSource() == convertButton && text.isEmpty() == false) {
   calcCount++;
   conversionCountLabel.setText("Conversion Count: " + calcCount);
}

Как я могу обработать это более эффективно, и убедиться, что calcCount действительно увеличивается в правильных условиях, а не независимо от того, происходит ли сбой анализа?

Редактировать -----------------------

Так как я не смог решить проблему, я предоставил небольшую программу ниже с основной функцией.и проблема, с которой я сталкиваюсь:

класс "thing1" - класс драйвера:

import java.io.IOException;

import javax.swing.JFrame;
import javax.swing.JLabel;


public class thing1 {

    public static void main(String[] args) throws IOException {

        JFrame frame = new JFrame("Thing");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        thing2 thing2 = new thing2();

        frame.getContentPane().add(thing2);

        frame.pack();
        frame.setVisible(true);
    }
}

класс "thing 2", включая Extends и соответствующих слушателей

import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;


@SuppressWarnings("serial")
public class thing2 extends JPanel {

    /**
     *  Declaring all variables and components to be used within the GUI
     */
    private JTextField conversionField;
    private JLabel resultLabel, conversionCountLabel, inputLabel;
    private JButton convertButton, clearButton;
    private int calcCount;
    private String text;
    double conversionFieldValue;
    private double result;

    thing2() {

        /**
         * Creating two listeners which will be used
         * "convertListener" is used for conversions
         * "convertDeleteListener" is used to set the values of conversionField, resultLabel, conversionCountLabel and calcCount
         *  all used to display details about number of conversions etc.
         */
        ActionListener convertListener = new ConvertListener();
        ActionListener convertDeleteListener = new convertDeleteListener();

        /**
         *  Creating inputLabel and conversionCountLabel
         */
        inputLabel = new JLabel("Enter value:");
        conversionCountLabel = new JLabel("Conversion Count: ");

        /**
         *  Creating both the convertButon and clearButton
         *  Adding listeners to both buttons which determine when they are clicked,
         *  and what action should be carried out when done so.
         */
        convertButton = new JButton("Convert");
        convertButton.addActionListener(convertDeleteListener);
        convertButton.addActionListener(convertListener); // convert values when pressed
        clearButton = new JButton("Clear");

        /**
         *  Creating both the resultLabel and conversionField
         */
        resultLabel = new JLabel();
        conversionField = new JTextField(5);

        /**
         *  Adding all created assets to the JFrame.
         *  Adding toolTips to each of the created assets.
         *  Adding Listeners to select assets to carry out certain tasks.
         */
        add(inputLabel);
        add(conversionField);
        conversionField.addActionListener(convertListener);
        add(convertButton);
        add(resultLabel);
        add(conversionCountLabel);
        add(clearButton);
        clearButton.addActionListener(convertDeleteListener);

        /**
         *  Creating size of JFrame.
         *  Setting background colour.
         */
        setPreferredSize(new Dimension(800, 80));
        setBackground(Color.WHITE);
    }

    public class ConvertListener implements ActionListener {

        @Override
        public void actionPerformed(ActionEvent event) {

            /**
             *  Trimming all leading and trailing white spaces from the text the user has input.
             */
            text = conversionField.getText().trim();

            if (text.isEmpty() == false) {
                /**
                 *  Simply trying to convert input to a double, if that fails outputting a Dialog box to users screen stating why
                 */
                try {
                    conversionFieldValue = Double.parseDouble(text);
                } catch (NumberFormatException e) {
                    calcCount = 0;
                    JOptionPane.showMessageDialog(null, "Error: the value entered may not be a valid number. \nPlease ensure that you are entering a valid double, with or without a decimal place.", "Conversion error", JOptionPane.ERROR_MESSAGE);
                    conversionCountLabel.setText("Conversion Count: " + calcCount);
                }


                // the factor applied during the conversion
                double factor = 0;

                // the offset applied during the conversion.
                double offset = 0;

                // Setup the correct factor/offset values depending on required conversion

                result = factor * conversionFieldValue + offset;

                //formatting the value to two decimal places.
                String numAsString = String.format ("%.2f", result);
                resultLabel.setText(numAsString);
            } else {
                if(text.isEmpty() == true) {
                    /**
                     *  if the text value is empty, simply display a dialog box stating so
                     */
                    calcCount = 0;
                    JOptionPane.showMessageDialog(null, "Error: the text input area cannot be empty.", "Text area is empty...", JOptionPane.ERROR_MESSAGE);
                    conversionCountLabel.setText("Conversion Count: " + calcCount);
                }
            }
        }
    }

    public class convertDeleteListener implements ActionListener{
        public void actionPerformed(ActionEvent e){

            /**
             *  Using e.getSource to determine which button was pressed, doing some actions depending on which it was.
             */
            if(e.getSource() == convertButton && text.isEmpty() == false) {
                calcCount++;
                conversionCountLabel.setText("Conversion Count: " + calcCount);
            } else 
                if(e.getSource() == clearButton) {
                    calcCount = 0;
                    conversionField.setText("");
                    resultLabel.setText("");
                    conversionCountLabel.setText("Conversion Count: " + calcCount);
                } 

        }
    }
}

Должно быть в состоянии скомпилировать это как есть, и если вы введете любой символ в поле, отличное от double, вы получите диалоговое окно с сообщением об ошибке - однако вы заметите, что «caclCount» по-прежнему увеличивается, даже если преобразование завершается неудачно.Результат будет отображаться как 00.00 из-за необходимости выключить огромный переключатель со всеми конверсиями - он рассчитывается правильно в полной программе, просто calcCount, с которым у меня возникла проблема.

Редактировать: теперь это было решено,спасибо всем за помощь:).

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...