gpt4 book ai didi

java - 检查字符串是否包含数值和字母值

转载 作者:搜寻专家 更新时间:2023-11-01 08:22:44 24 4
gpt4 key购买 nike

我正在尝试检测字符串是否具有 NumericValueAlphaValue。如果它只是数字,则 AmountBoolean = true,如果它是数字和 Alpha,则 AmountBoolean = false。我找不到让这个工作的方法。看来我找到了一种方法,但在运行时崩溃,在 logcat 中声明 onClick if 语句是一个问题,但我不知道它为什么或如何。

用于帮助解决此问题的链接是:

How to check if a string contains only digits in Java

Java - See if a string contains any characters in it

Tell if string contains a-z chars

主要 Activity ;

public class MainActivity extends AppCompatActivity {

Button Enter;
EditText eName,eDate,eAmount;
ListView lDebtList;
TextView tName,tDate,tAmount;

Boolean AmountBoolean = false;
String currentDate,name,amount,date;
Toast toastName,toastDate,toastAmount;

ArrayList<String> AmountlistItems = new ArrayList<String>();
ArrayList<String> DateListItems = new ArrayList<String>();
ArrayList<String> NameListItems = new ArrayList<String>();

ArrayAdapter<String> AmountAdapter;
ArrayAdapter<String> DateAdapter;
ArrayAdapter<String> NameAdapter;

String numRegex = ".*[0-9].*";
String alphaRegex = ".*[A-Z].*";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

Enter = findViewById(R.id.Enter);
eAmount = findViewById(R.id.eAmount);
eDate = findViewById(R.id.eDate);
eName = findViewById(R.id.eName);
lDebtList = findViewById(R.id.lDebtList);
tAmount = findViewById(R.id.tAmount);
tDate = findViewById(R.id.tDate);
tName = findViewById(R.id.tName);

eAmount.clearFocus();
eDate.clearFocus();
eName.clearFocus();

currentDate = new SimpleDateFormat("MM-dd-yyyy", Locale.getDefault()).format(new Date());

tAmount.setText("Amount:");
tDate.setText("Date Owed");
tName.setText("Name:");

eAmount.setHint("$$$");
eDate.setHint(currentDate);
eName.setHint("John Doe");


amount = eAmount.getText().toString();
date = eDate.getText().toString();
name = eName.getText().toString();



if (amount.contains(numRegex) && !amount.contains(alphaRegex)) {
AmountBoolean = true;
}
if(amount.matches(numRegex) && amount.contains(alphaRegex)){
AmountBoolean = false;
}


AmountAdapter = new ArrayAdapter<String>(MainActivity.this,android.R.layout.simple_list_item_1, AmountlistItems);
lDebtList.setAdapter(AmountAdapter);
}

public void onEnter(View view){
if(AmountBoolean){
//AmountAdapter.add(amount);
AmountAdapter.add(eAmount.getText().toString());
AmountAdapter.notifyDataSetChanged();
}

if(!AmountBoolean){
toastAmount = Toast.makeText(this, "Please correct Amount Owed", Toast.LENGTH_SHORT);
toastAmount.show();

}


}


}

感谢任何和所有的帮助,此外,如果有更简单的方法来实现这一点,请不要犹豫,展示如何。我知道之前有人问过这个问题,但我花了几个小时尝试各种方法,但都没有奏效,我正在求助于此。

最佳答案

使用下面的正则表达式:

只检查数字

^[0-9]+$

只检查字母

^[a-zA-Z]+$

检查字符串是否包含字母

.*([a-zA-Z]).*

检查字符串是否为字母数字

^[a-zA-Z0-9]+$

关于java - 检查字符串是否包含数值和字母值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48859898/

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