gpt4 book ai didi

Java - 检查 int 是否为空

转载 作者:行者123 更新时间:2023-12-01 18:08:19 24 4
gpt4 key购买 nike

我正在尝试在 android studio 中对 int 进行字段验证。该字段的代码如下;

public class Register extends ActionBarActivity implements View.OnClickListener {

EditText etName, etAge, etUsername, etPassword;
Button bRegister;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);

etName = (EditText) findViewById(R.id.etName);
etAge = (EditText) findViewById(R.id.etAge);
etUsername = (EditText) findViewById(R.id.etUsername);
etPassword = (EditText) findViewById(R.id.etPassword);
bRegister = (Button) findViewById(R.id.bRegister);

bRegister.setOnClickListener(this);
}

@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.bRegister:
String name = etName.getText().toString();
String username = etUsername.getText().toString();
String password = etPassword.getText().toString();
String ageText = etAge.getText().toString();
if(! TextUtils.isEmpty(ageText)) {
int age = Integer.parseInt(ageText);
}

if(name.length()==0)
{
etName.requestFocus();
etName.setError("Please don't leave the name field empty.");
}else if(username.length()==0)
{
etUsername.requestFocus();
etUsername.setError("Please don't leave the username field empty.");
}else if(password.length()==0)
{
etPassword.requestFocus();
etPassword.setError("Please don't leave the password field empty.");
}/*else if(age == null)
{
etAge.requestFocus();
etAge.setError("Please don't leave the age field empty.");
}*/
else if(!name.matches("[a-zA-Z]"))
{
etName.requestFocus();
etName.setError("Please only use alphabetic characters");
}else{
User user = new User(name, age, username, password);
registerUser(user);
}


break;
}
}

private void registerUser(User user) {
ServerRequest serverRequest = new ServerRequest(this);
serverRequest.storeUserDataInBackground(user, new GetUserCallback() {
@Override
public void done(User returnedUser) {
Intent loginIntent = new Intent(Register.this, Login.class);
startActivity(loginIntent);
}
});
}
}

但是我无法验证 int 年龄,它一直给我这个错误;

java.lang.NumberFormatException: Invalid int: ""

用户类别

public class User {
String name, username, password;
int age;

public User(String name, int age, String username, String password) {
this.name = name;
this.age = age;
this.username = username;
this.password = password;
}

最佳答案

试试这个:

String ageText = etAge.getText().toString();
int age = 0;

if(! TextUtils.isEmpty(ageText)) // If EditText is not empty
age = Integer.parseInt(ageText); // parse its content to integer

// Continue validation...

而不是

int age = Integer.parseInt(etAge.getText().toString());

关于Java - 检查 int 是否为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34705246/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com