0
  1. textSeventh is a JTextField
  2. I am using a submit button with an action listener

Code:

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);
        }
    }
}
mvmn
  • 3,717
  • 27
  • 30
GSGlv
  • 1
  • 1
  • 7
    @GSGIv Could you add the error you get here..? – Juliyanage Silva Jun 04 '18 at 04:18
  • Do you do this in an `ActionListener` or did you just call it immediately after creating the `JTextField`? – MadProgrammer Jun 04 '18 at 04:21
  • 1) For better help sooner, post a [MCVE] or [Short, Self Contained, Correct Example](http://www.sscce.org/). 2) For the sake of the user, offer them a `JSpinner` with `SpinnerNumberModel` (instead of a text field). – Andrew Thompson Jun 04 '18 at 09:13
  • favoriteLetter = lastNameInput.toUpperCase().charAt(0); ... System.out.println("Your favorite letter is " + favoriteLetter + " ."); Do you see this System.out message? Because the charAt(0) looks extremely suspicious. I'd guess this is where your exception is being thrown from. – Rick Jun 05 '18 at 05:55

1 Answers1

1

If you're getting a NumberFormatException then java can't parse whatever it is as a number.

Other things to check for would be empty strings "" or null strings (in which case it may throw a null pointer exception).

Maybe also check if there is spurious whitespace - get rid of it with a trim e.g.

//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);
Rick
  • 576
  • 3
  • 12
  • Here is part of the error message: Exception in thread "AWT-EventQueue-0" java.lang.StringIndexOutOfBoundsException: String index out of range: 0 – GSGlv Jun 04 '18 at 12:40
  • The error message is still present with the edited code above – GSGlv Jun 04 '18 at 12:53
  • in which line actually you are getting the error message? Can you post the entire edited code here? – Sivanandham Jun 04 '18 at 13:03
  • And one more thing. StringIndexOutOfBoundsException means your trying to retrieve invalid index. Check length of the String before parsing into integer. – Sivanandham Jun 04 '18 at 13:07
  • I am trying to input an integer or double value such as 12 into the textField and the convert it from a String to an integer. – GSGlv Jun 04 '18 at 13:13
  • Can you post the full code or the full error message ? – Sivanandham Jun 04 '18 at 13:17
  • Arrays start counting at position 0, for historical reasons involving pointers and memory locations, which I can explain in more detail if required but not relevant here. So index position number 0 is the first character in the string. If that is out of bounds (e.g. past the end of the array) then to me that indicates that the array is empty - e.g. it's just "" or the empty string. But I would have thought the library would take better care of that. Also, I would expect to see "There's nothing there!!" on the output - since we are specifically checking for that case. – Rick Jun 04 '18 at 23:29
  • I tried to make a case duplicating the code to see what would happen if the string was empty: String s = ""; try { System.out.println("wibble " + Integer.parseInt(s)); } catch (Exception e) { System.out.println(e); } And what happens is that I get the following exception: java.lang.NumberFormatException: For input string: "" So I think the array index out of bounds error is coming from somewhere else in your code. Uncomment the printing of the stack trace in the above code and post it, and that'll tell us where it's actually coming from – Rick Jun 04 '18 at 23:33
  • A quick google search on: Exception in thread "AWT-EventQueue-0" java.lang.StringIndexOutOfBoundsException: String index out of range: 0 Shows that it's typically because the programmer is somewhere taking the substring of the string. So if you're doing some string manipulation before getting to the Integer.parseInt bit then that is probably where the problem is. – Rick Jun 04 '18 at 23:40
  • I started over with getting the favorite number portion. The issue I think is with being able to get the double value dollars. I posted the code above and it does not have anything with trying to change the value. Only the getText method. This is is the first line of the error:java.lang.NumberFormatException: For input string: "12.30" – GSGlv Jun 05 '18 at 20:20
  • You're probably getting the NumberFormatException because the string is empty. Do a comparison to an empty string - e.g. if (s.equalsIgnoreCase("")) { System.out.println("Complain bitterly"); } – Rick Jun 05 '18 at 23:18
  • Your code works as it is - but there is no parseInt anywhere in the code. It just outputs first name. You should provide COMPLETE code if you want an answer. – mvmn Mar 08 '19 at 21:22