简体   繁体   中英

How can check if a java string contains numbers and letters?

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    editText = findViewById(R.id.editTextName);
    textView = findViewById(R.id.textViewOne);
    button = findViewById(R.id.buttonOne);
    view = findViewById(R.id.snackbar_action);
    String x = editText.getText().toString();
    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {//Checking if edit text field is left empty.
            if (editText.getText().toString().equals("")) {
                Snackbar.make(view, R.string.text_label, Snackbar.LENGTH_SHORT).show();
            }//Checking if editText field is numeric.
            else if (TextUtils.isDigitsOnly(x)){
                Snackbar.make(view, R.string.text_number, Snackbar.LENGTH_SHORT).show();
            } else {
                textView.setText(NATOConverter("" + editText.getText().toString()));
            }
        }
    });
}

Hello guys im struggling trying to figure out how to check if a my edittext value contains letters and numbers im trying to display a snackbar if the user enters for example "JDF23D" telling them to remove the numbers but my error is no matter what it stays on that else if what would you suggest?

If you want to check whether the string contains a number, you should use this,

public boolean containsDigit(String x){
for(int i = 0; i < x.length(); i++){
        if(48 <= (int) (x.charAt(i)) <= 57)
            return true;
}
return false;
}

Returns true if even one character is a number, else false.

Try next code

if (editText.getText().toString().matches(".*[0-9].*")){
            //some code
        }
        else{
           //some code 
        }

You use this method:

TextUtils.isDigitsOnly(x)

but this method checks if your string only contains digits. So your example "JDF23D" will return false .

You can take a look at this post

尝试更简单的

boolean match = Pattern.compile("\\d+").matcher(s).find();

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM