Home > Blockchain >  exception in thread, for input string
exception in thread, for input string

Time:10-01

I want to get the text from a JTextField and turn it into a string in order to multiply the integer with another number when the user clicks on a button.

This is what I have now:

firstTextField = new JTextField();
firstTextField.setBounds(40, 200, 100, 40);
firstTextField.setText("Enter amount");
stringTextField = firstTextField.getText();
integerTextField = Integer.parseInt(stringTextField);

if (e.getSource() == secondButton) {
    System.out.println(Integer.parseInt(firstTextField.getText())  45);
}

What did I do wrong?

The error message:

Exception in thread "main" java.lang.NumberFormatException: For input string: "Enter amount"
at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:67)
at java.base/java.lang.Integer.parseInt(Integer.java:660)
at java.base/java.lang.Integer.parseInt(Integer.java:778)
at com.company.MyClass.<init>(MyClass.java:49)
at com.company.Main.main(Main.java:7)

CodePudding user response:

Because right now your code set a text ("Enter amount") in a JTextField and then retrieves it and try to convert it to an integer, so "Enter amount" is not an integer.

Try to retrieve it AFTER the event you are capturing :)

CodePudding user response:

@jakob : First of all , I would strongly recommend you to go through the basics of java. Now Please take a look at the examples given below.

Examples:

1.String str1 = "helloworld"; // a variable of type String can have only alphabets
2.String str2 = "Hello123";  // can also have alpha-numeric 
3.String str3 = "@hello$123";  // can also have special characters and alpha-numeric as well
4.String str4 = "1234";  // Can have only numbers
5.String str5 = "99"; // Can also have only numbers

All the above examples are of type String.

If you wanna parse a string to an Integer type you can only do it with the Strings given in Ex : 4 and 5.

The Given String should only contain Numbers when parsing it to an Integer,Double,Long or Float, If not Exception will be thrown.

  • Related