【问题标题】:If a string ends with any value of an array Java [closed]如果字符串以数组Java的任何值结尾[关闭]
【发布时间】:2021-02-01 02:19:48
【问题描述】:

我有一个数组

String[] Array = {"+", "-", "*", "/"}

和一个 EditText 字符串

operation = (EditText) findViewById(R.id.operation);

所以,我有一个按钮,我想在其中添加一个 if 语句,例如:

    Button.setOnLongClickListener(new View.OnLongClickListener() {
                @Override
                public boolean onLongClick(View v) {
                    if(operation.getText().toString().endsWith(Array.toString())){
                        prinln("Example"); }
                }
            });

我不知道如何解决这个问题。如何编写字符串以任何数组值结尾的 if 语句并使其工作

【问题讨论】:

  • 我尝试调试 if(operation.getText().toString().endsWith(Arrays.toString(Array)))。但它也不起作用
  • 您需要遍历数组并单独检查每个数组元素。
  • 我必须这样做: if (string.endsWith(Array[1]) || string.endsWith(Array[2])? 我想过,但没有更复杂的和更短的方式?
  • 这不是迭代。你需要一个循环。
  • 好的,我想我明白了,我会试试的

标签: java android android-studio


【解决方案1】:

如果您真的不想使用循环您可以将数组值保存为键,并将您想要的答案保存为值。 然后直接使用地图

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)));

【讨论】:

    【解决方案2】:

    您需要遍历您的数组,这将获取数组中的每个字符串并检查您的字符串是否以数组中的字符串 's' 结尾

    for (String s: Array) {
            //Do your stuff here
            if(yourString.endsWith(s)){
                println(example);
            }
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-01-04
      • 1970-01-01
      • 2013-04-07
      • 2015-05-16
      • 1970-01-01
      • 1970-01-01
      • 2017-11-08
      • 1970-01-01
      相关资源
      最近更新 更多