如何从给定值找到的Java String数组的索引? [英] How to find index of STRING array in Java from a given value?

查看:2086
本文介绍了如何从给定值找到的Java String数组的索引?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否有在数组中的本地方法的Java拿到表的索引给定值?

比方说我的表包含这些字符串:

 公共静态最后的String []类型= {
        轿车,
        紧凑,
        跑车,
        面包车,
        SUV,
        换股,
        货物,
        其他
    };

让我们说,用户必须进入汽车的类型和然后在后台程序采用该字符串和得到的它的阵列中的位置。

因此​​,如果人进入:轿车
它应该采取的立场0和商店的它由我的程序创建汽车的对象...


解决方案

 字符串carName = //插入code在这里
INT指数= -1;
的for(int i = 0; I< TYPES.length;我++){
    如果(TYPES [I] .equals(carName)){
        指数= I;
        打破;
    }
}

索引之后是你的车的数组索引,或者-1,如果它不存在。

I wanted to know if there's a native method in array for Java to get the index of the table for a given value ?

Let's say my table contains these strings :

public static final String[] TYPES = {
        "Sedan",
        "Compact",
        "Roadster",
        "Minivan",
        "SUV",
        "Convertible",
        "Cargo",
        "Others"
    };

Let's say the user has to enter the type of car and that then in the background the program takes that string and get's it's position in the array.

So if the person enters : Sedan It should take the position 0 and store's it in the object of Cars created by my program ...

解决方案

String carName = // insert code here
int index = -1;
for (int i=0;i<TYPES.length;i++) {
    if (TYPES[i].equals(carName)) {
        index = i;
        break;
    }
}

After this index is the array index of your car, or -1 if it doesn't exist.

这篇关于如何从给定值找到的Java String数组的索引?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆