已解决:我目前正在使用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;
}
答案 0 :(得分:0)
您应该使用Integer#parseInt
方法:
int contactnumber = Integer.parseInt(contactfield.getText());
Integer#parseInt
取String
并将其转换为原始int
(如果它是有效数字)。如果该数字无效,则会抛出NumberFormatException
。
/**
* 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.
*/
答案 1 :(得分:0)
最简单的方法是将其作为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
}
}