[英]Getting a numeric value form a text field
解决:我目前正在使用Netbeans(JFrames)编写程序,我需要使用'.get'之一从文本字段获取数值。
新问题:在执行contactumber的'if语句'时,给我一个错误,指出不能取消引用int。 有什么建议么 ?
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;
}
您应该使用Integer#parseInt
方法:
int contactnumber = Integer.parseInt(contactfield.getText());
Integer#parseInt
接受一个String
并将其转换为原始int
如果它是有效数字)。 如果数字无效,则将引发NumberFormatException
。
说明文件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.
*/
最简单的方法是将其获取为String并使用Integer.parseInt()
方法转换为数字。
String contactNumberStr = contactfield.get();
if (contactNumberStr != null) {
try {
int contactNumber = Integer.parseInt(contactNumberStr);
} catch (NumberFormatException e) {
// contactfield is not having a number
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.