Преобразование строкового ввода в Integer из JTextField с Integer.parseInt, но все еще получающего сообщение об ошибке - PullRequest
0 голосов
/ 04 июня 2018
  1. textSeventh - это JTextField
  2. Я использую кнопку отправки с прослушивателем действий

Код:

String amountInput = textSeventh.getText();
System.out.println(amountInput);

import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;

public class UI2 implements ActionListener {

    public static void main(String[] args) {
        // Dont use the static context. Make an instance variable and call your method.
        UI ui = new UI();
        ui.makeUI();
    }

    static String questionFirst = "What is your first name?";
    static String questionSecond = "What is your last name?";
    static String questionThird = "What month were you born? Enter one     number.";
    static String questionFourth = "What year were you born?";
    static String questionFifth = "What day were you born?";
    static String questionSixth = "What is your bank account number";
    static String questionSeventh = "How much is in your bank account?   Include decimals.";

    public void makeUI() {
        makeBox(questionFirst, questionSecond, questionThird, questionFourth, questionFifth, questionSixth, questionSeventh);
    }

    static JFrame frame = new JFrame("FortuneTeller");
    static JPanel panel = new JPanel(new GridBagLayout());

    static JLabel labelFirst = new JLabel();
    static JTextField textFirst = new JTextField(50);

    static JLabel labelSecond = new JLabel();
    static JTextField textSecond = new JTextField(50);

    static JLabel labelThird = new JLabel();
    static JTextField textThird = new JTextField(50);

    static JLabel labelFourth = new JLabel();
    static JTextField textFourth = new JTextField(50);

    static JLabel labelFifth = new JLabel();
    static JTextField textFifth = new JTextField(50);

    static JLabel labelSixth = new JLabel();
    static JTextField textSixth = new JTextField(50);

    static JLabel labelSeventh = new JLabel();
    static JTextField textSeventh = new JTextField(50);

    static JButton submitButton = new JButton("Submit");

    static String firstName;
    static String lastName;
    static String month;
    static String year;
    static String day;
    static String bankNum;
    static String amount;

    static char favoriteLetter;
    static String both;
    static String reverse;
    static String favoritePalindrome;
    static String favoriteColor; // red or blue
    static String favoriteAnimal; // cat or dog
    static String favoriteCar; // F150 or Minivan
    static String favoriteNum;
    static int intDollars;
    static String math;

    public void makeBox(String questionFirst, String questionSecond, String questionThird, String questionFourth, String questionFifth, String questionSixth,
            String questionSeventh) {
        frame.add(panel);
        frame.setVisible(true);
        frame.setSize(700, 200);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        panel.setLayout(new GridLayout(8, 1));
        // Now I am only trying to get input from the first box
        panel.add(labelFirst);
        labelFirst.setText(questionFirst);
        panel.add(textFirst);

        // This is the advice from my school's computer science teacher when we thought
        // that
        // the program was printing the initial value inside the textfield, nothing.
        // Enter text
        // Wait for submit button
        // Then getText();
        // I was still unable to get it to work

        panel.add(labelSecond);
        labelSecond.setText(questionSecond);
        panel.add(textSecond);

        // get text will be empty here. You should be calling this after the user enters text and clicks submit.
        lastName = textSecond.getText();

        panel.add(labelThird);
        labelThird.setText(questionThird);
        panel.add(textThird);

        // get text will be empty here. You should be calling this after the user enters text and clicks submit.
        month = textThird.getText();

        panel.add(labelFourth);
        labelFourth.setText(questionFourth);
        panel.add(textFourth);

        // get text will be empty here. You should be calling this after the user enters text and clicks submit.
        year = textFourth.getText();

        panel.add(labelFifth);
        labelFifth.setText(questionFifth);
        panel.add(textFifth);

        // get text will be empty here. You should be calling this after the user enters text and clicks submit.
        day = textFifth.getText();

        panel.add(labelSixth);
        labelSixth.setText(questionSixth);
        panel.add(textSixth);
        // get text will be empty here. You should be calling this after the user enters text and clicks submit.
        bankNum = textSixth.getText();

        panel.add(labelSeventh);
        labelSeventh.setText(questionSeventh);
        panel.add(textSeventh);
        // get text will be empty here. You should be calling this after the user enters text and clicks submit.
        amount = textSeventh.getText();

        // need to add an actionListener to the button
        submitButton.addActionListener(this);

        panel.add(submitButton);
        frame.pack();
    }

    @Override
    public void actionPerformed(ActionEvent e) {

        // TODO Auto-generated method stub

        // You need to get the source of the button. (JButton) e.getSource();
        JButton buttonPressed = (JButton) e.getSource();
        if (buttonPressed == submitButton) {
            String firstNameInput = textFirst.getText();
            System.out.println(firstNameInput);
        }
    }
}

1 Ответ

0 голосов
/ 04 июня 2018

Если вы получаете NumberFormatException, то java не может анализировать, что бы это ни было, как число.

Другие вещи, которые нужно проверить, это пустые строки "" или нулевые строки (в этом случае это может привести кисключение нулевого указателя).

Возможно, также проверьте, есть ли ложные пробелы - избавьтесь от него с помощью обрезки, например

//get favorite number
String amountInput = textSeventh.getText();

if (amountInput == null) {
    System.err.println("amountInput was null, no point continuing");
    return;
}

// make it a bit more obvious if there's whitespace
System.out.println("amountInput = +++" + amountInput + "+++");

amountInput = amountInput.trim();

if (amountInput.equalsIgnoreCase("")) {
    System.err.println("There's nothing there!!");
}

int dollars = -1337;
try {
    dollars = Integer.parseInt(amountInput);
} catch (Exception e) {
    System.err.println("Error when parsing value.\n" + e);
    // optional
    // e.printStackTrace();
}
System.out.println(dollars);
...