本文介绍了如何从给定的值中找到 Java 中 STRING 数组的索引?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想知道数组中是否有一种用于 Java 的本地方法来获取给定值的表索引?
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.
所以如果这个人进入:Sedan它应该占据位置 0 并将其存储在我的程序创建的 Cars 对象中...
So if the person enters : SedanIt 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;
}
}
在此index
之后是您的汽车的数组索引,如果不存在则为-1.
After this index
is the array index of your car, or -1 if it doesn't exist.
这篇关于如何从给定的值中找到 Java 中 STRING 数组的索引?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!