簡體   English   中英

如何檢查兩個不同數組的相等索引並輸入正確的值

[英]How to check the equal indexes of two different Arrays and put the correct value

考慮到我有兩個數組,例如:

String [] countrys = {"USA", "AUSTRALIA"}; // indexes 0,1

String [] numberStates = {"50", "6"}; //indexes 0,1

我對此數組有點業余,並為相等的索引分配了正確的值。

我正在尋找的是分配正確的值,例如,從美國國家/地區分配50個州,下一個是Austrlia分配6個州。

我已經搜索了類似的教程,但是我仍然不清楚如何分配2個數組的正確索引。

 //complete code snippet

 Unit<Length> AddCorrectNumberStateToCountry = null;

 String queryCountry = “USA”

 String[] countrys = {"USA", "AUSTRALIA"};

 String[] numberStates = {"50", "6"};


 for(int t = 0; t < countrys.length; t++) {
 if (queryCountry.contains(countrys [t])) {

 AddCorrectNumberStateToCountry = STATES.plus(?????); 
 //here need know put exactly numberStates value by check index  STATES.plus(?)                 

 }
 }

我向Elliott Frisch道歉,他是對的,我的錯是我的

由於某些神秘的原因,第1位的狀態值使我感到無用

double [] numberStates = {1 /* <---- nuller point 
i change to 0 and solve my problem */, 
50, 6};

還要將數組從int更改為double


艾略特·弗里施(Elliot Frisch)

首先,您應該確定值的適當類型。 多個狀態可以表示為一個int(不清楚為什么要使用String或Unit)。 “國家”的復數形式是“國家”。 你可以做類似的事情,

String queryCountry = "USA";
String[] countries = { "USA", "AUSTRALIA" };
int[] numberStates = { 50, 6 };
int statesInCountry = -1;
for (int t = 0; t < countries.length; t++) {
if (countries[t].contains(queryCountry)) {
    statesInCountry = numberStates[t];
}
}

但是使用Map或自定義Java類型會更好。

非常感謝Elliot Frisch。

您應該創建一個這樣的類:

public class CountryInfo {
private String name;
private int numberOfStates;

public CountryInfo(String name, int numberOfState)  {
    this.name = name;
    this.numberOfStates = numberOfStates;
}

public String getName() {
    return name;
}

public int getNumberOfStates() {
    return numberOfStates;
}
}

然后

String [] countries = {"USA", "AUSTRALIA"}; // indexes 0,1
String [] numberStates = {"50", "6"}; //indexes 0,1
List<CountryInfo> list = new ArrayList<>();

for (int i = 0; i < numberStates.length; i++) {
    list.add(new CountryInfo(countries[i]), numberStates[i]);
}

要訪問元素,您可以:

list.get(0).getName();
list.get(0).getNumberOfStates();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM