英文:
If a string ends with any value of an array Java
问题
I have an array<br>
String[] Array = {"+", "-", "*", "/"}
and an EditText string<br>
operation = (EditText) findViewById(R.id.operation);
So, I have a button where I want to add an if statement like: <br>
Button.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
if(operation.getText().toString().endsWith(Array.toString())){
prinln("Example"); }
}
});
I don't know how to make this right. How to write the if statements where the String ends with any value of array and make it work
英文:
I have an array<br>
String[] Array = {"+", "-", "*", "/"}
and an EditText string<br>
operation = (EditText) findViewById(R.id.operation);
So, I have a button where I want to add an if statement like: <br>
Button.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
if(operation.getText().toString().endsWith(Array.toString())){
prinln("Example"); }
}
});
I don't know how to make this right. How to write the if statements where the String ends with any value of array and make it work
答案1
得分: 1
你需要遍历你的数组,这将取出数组中的每个字符串,并检查你的字符串是否以数组中的字符串"s"结尾。
for (String s: Array) {
// 在这里处理你的操作
if (yourString.endsWith(s)) {
println(example);
}
}
英文:
You need to loop through your array, this will take each of the string in the array and check if your String ends with the String 's' from the array
for (String s: Array) {
//Do your stuff here
if(yourString.endsWith(s)){
println(example);
}
}
答案2
得分: 1
如果您真的不想使用循环,您可以将数组的值保存为键,将您想要的答案保存为值,存储在一个映射中。
然后直接使用这个映射。
HashMap<char, String> operandMap = new HashMap<char, String>();
operandMap.put('+', "加法");
operandMap.put('-', "减法");
operandMap.put('*', "乘法");
operandMap.put('/', "除法");
operandMap.put('%', "取余");
println(operandMap.get(operation.getText().toString().charAt(operation.getText().toString().length - 1)));
英文:
If you really don't want to use a loop, you can save array values as keys and your desired answers as values in a map.
And then use the map directly.
HashMap<char, String>operandMap = new HashMap<char,String>();
operandMap.put('+',"Addition");
operandMap.put('-',"Subtraction");
operandMap.put('*',"Multiplication");
operandMap.put('/',"Division");
operandMap.put('%',"Modulus");
println(operandMap.get(operation.getText().toString().charAt(operation.getText().toString().length-1)));
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论