我正在尝试获取有关用户的一些基本信息,例如高度、体重等。
我正在使用 EditText 对象和 getText()
从用户键入的内容中检索文本。然后我将其转换为字符串,最后使用 Integer.parseint(String) 将所有内容转换为 int。下面是我试图做的一个例子,如果这令人困惑的话。
if((height.getText().length() > 0) && (???)) {
mHeight = Integer.parseInt(height.getText().toString());
} else {
Toast.makeText(getBaseContext(), "Please enter your height, in inches, rounded to the nearest inch", Toast.LENGTH_SHORT).show();
canContinue = -1;
}
我使用 height.getText().length() > 0
来确保用户至少在字段中输入了一些内容,但如果用户输入字符,则程序会崩溃。
(???) 是我试图在这里完成的断言,当结果不是有效的 int 时,它将返回 false。另请注意,我在这里将 mHeight 初始化为原始 int int mHeight
注意:height是一个EditText
对象,我像这样初始化它:height = (EditText) findViewById(R.id.height);
最佳答案
不需要进行一些复杂的验证,我只是尝试解析并捕获任何异常。
//test that the value is not empty and only contains numbers
//to deal with most common errors
if(!height.getText().isEmpty() && height.getText().matches("\\d+")) {
try {
mHeight = Integer.parseInt(height.getText());
} catch (NumberFormatException e) { //will be thrown if number is too large
//error handling
}
}
关于java - 确保 Integer.parseInt(String) 是 java 中的有效 int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44547737/