简体   繁体   English

如何将用户的输入值与数组中的值进行比较

[英]How to compare input values from user with values in array

I want to use existing array element as switch case rather giving constant string value to switch case 我想使用现有的数组元素作为开关案例,而不是给开关案例提供恒定的字符串值

I have values in resource string array that I used to display, and user has to select from these display values, now I want to compare the input value that I saved in shared preference and the values that I have in array resource, I wrote something like this but it didn't work 我曾经显示过资源字符串数组中的值,用户必须从这些显示值中进行选择,现在我想比较保存在共享首选项中的输入值和我保存在数组资源中的值,我写了一些东西这样,但没有用

private static String activity;
private static int result;
activity = SharedPrefUtils.getActivityLevel(context);

String[] activities 
= context.getResources().getStringArray(R.array.activity);

switch (activity){
      //something like getting values from array
        case activities[0]:
            result = 0;
            break;
        case activities[1]:
            result = 200;
            break;
        case activities[2]:
            result = 300;
            break;
    }

    return result;

Instead of iterating through an array , you can convert it into a List and use indexOf to get the element index, eg: 无需遍历array ,您可以将其转换为List并使用indexOf获取元素索引,例如:

String[] activities = context.getResources().getStringArray(R.array.activity);
List<String> activitiesList = Arrays.asList(activities);
int index = activitiesList.indexOf(activity);

This is what the javadoc says: 这是javadoc所说的:

Returns the index of the first occurrence of the specified element in this list, or -1 if this list does not contain the element. 返回指定元素在此列表中首次出现的索引;如果此列表不包含该元素,则返回-1。 More formally, returns the lowest index i such that (o==null ? get(i)==null : o.equals(get(i))), or -1 if there is no such index. 更正式地,返回最低索引i,使其(o == null?get(i)== null:o.equals(get(i))),或者如果没有这样的索引,则返回-1。

So, you can base your logic on index value. 因此,您可以将逻辑基于index值。

Another approach would be to use a Map<Integer, String> and pass the Integer key to the method based on whichever value is selected by a user. 另一种方法是使用Map<Integer, String>并根据用户选择的值将Integer键传递给方法。

First of all make sure your "activity" String and the items of "activities" array are returning you some values. 首先,请确保您的“活动”字符串和“活动”数组项正在返回一些值。 Try to print the values to check that. 尝试打印这些值以进行检查。 If all of them are returning you values then you can compare String in this way: 如果所有这些都返回您的值,则可以通过以下方式比较String:

if (activity.equalsIgnoreCase(activities[0]){
   Log.e("Matched" , "Yeah, it matched");
}

You can match your all String values one by one in this way. 您可以通过这种方式一一匹配所有的String值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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