SOLVED: I'm currently working on a program using Netbeans(JFrames) and I need to get a numeric value form a text field by using one of the '.get'.
NEW PROBLEM: When doing the 'if statement' of the contactumber it is giving me an error saying that an int cannot be dereferenced. Any suggestions ?
namevalidation.setText(""); //Set text for the label
surnamevalidation.setText(""); //Set text for the label
contactvalidation.setText(""); //Set text for the label
String name = namefield.getText(); //Get text form a textfield
String surname = surnamefield.getText(); //Get text form a textfield
int contactnumber = Integer.parseInt(contactfield.getText()); //Getting the numeric value form the textfield
boolean passed=true;
if(name.isEmpty())//Checking if the name or surname is empty
{
namevalidation.setText("Please enter your name!");
passed = false;
}
if(surname.isEmpty())
{
surnamefield.setText("Please enter your surname!");
passed = false;
}
if(contactnumber.isEmpty()) //THIS IS GIVING ME AN ERROR
{
contactfield.setText("Please enter your number!");
passed = false;
}
You should use the Integer#parseInt
method:
int contactnumber = Integer.parseInt(contactfield.getText());
The Integer#parseInt
takes a String
and converts it into the primitive int
if it is a valid number. If the number isn't valid a NumberFormatException
will be thrown.
Documentation Integer#parseInt
:
/**
* Parses the string argument as a signed decimal integer. The
* characters in the string must all be decimal digits, except
* that the first character may be an ASCII minus sign {@code '-'}
* ({@code '\u005Cu002D'}) to indicate a negative value or an
* ASCII plus sign {@code '+'} ({@code '\u005Cu002B'}) to
* indicate a positive value. The resulting integer value is
* returned, exactly as if the argument and the radix 10 were
* given as arguments to the {@link #parseInt(java.lang.String,
* int)} method.
*
* @param s a {@code String} containing the {@code int}
* representation to be parsed
* @return the integer value represented by the argument in decimal.
* @exception NumberFormatException if the string does not contain a
* parsable integer.
*/
Simplest way to do that will be to get it as a String and convert to a number using Integer.parseInt()
method.
String contactNumberStr = contactfield.get();
if (contactNumberStr != null) {
try {
int contactNumber = Integer.parseInt(contactNumberStr);
} catch (NumberFormatException e) {
// contactfield is not having a number
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.