gpt4 book ai didi

基于Json文件的Java非重复数组

转载 作者:行者123 更新时间:2023-11-30 00:19:37 24 4
gpt4 key购买 nike

目前,我还是一名大学生,正在为这个实验室项目苦苦挣扎。事实上,我完成了这个实验,但我想挑战一下自己,在我的项目中做一些额外的事情。我有这样的 JSON 文件:

{
"human":
[
{"name":"Richard",
"age":"16",
"job":"student",
"height":"160cm"
},
{"name":"Cindy",
"age":"17",
"job":"student",
"height":"150cm"
},
{"name":"Yuan",
"age":"20",
"job":"teacher",
"height":"180cm"
},
{"name":"Kathy",
"age":"18",
"job":"student",
"height":"175cm"
},
{"name":"Lee",
"age":"23",
"job":"teacher",
"height":"165cm"
},

在我的 XML 代码中,我的布局如下:

Spinner job
Spinner name
Textview txtview
Textview dispInfo

这就是我试图让我的微调器只做老师和学生的工作的方法,但是,它不起作用...

    JSONObject myJSON_object = new JSONObject(myText);

//the main JSON object is/includes an array
//extract that array
final JSONArray myJSON_array = myJSON_object.getJSONArray("human");

//temporarily array for Nettle Spinner
String[] temp = new String[myJSON_array.length()];
for (int i=0; i < myJSON_array.length(); i++){
try{
//get an individual element of the JSON array
JSONObject aJSON_element = myJSON_array.getJSONObject(i);
//get the individual properties of the JSON element
String jsJob = aJSON_element.getString("job");
temp[i] = jsJob;

}
catch (JSONException e)
{
Toast.makeText(getBaseContext(), "Dude, you have to know what the JSON looks like to parse it", Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
}

//actually how the array gonna be in
String[] forJob = null;
for (int i=0; i < temp.length; i++){
boolean duplicate = false;
int b = 0;
while (b < i){
if (temp[i] == temp[b]) {
duplicate = true;
b++;
}
}
if (duplicate == false) {
forNettle[i] = temp[i];
}
}

//associate the full name with the listView
Spinner spJob = (Spinner) findViewById(R.id.spNettle);
Spinner spName = (Spinner) findViewById(R.id.spCate);


ArrayAdapter<String> arrJob = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, forJob);
arrJob.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // The drop down view
spJob.setAdapter(arrJob);

最佳答案

去除重复项的方法:

int lastIdx = 0;
String[] result = new String[temp.lenght];
mainLoop: for(int i =0; i < temp.length; i++) {
for(int j = 0; j < lastIdx; j++)
if(result[j].equals(temp[i])) continue mainLoop;
result[lastIdx++] = temp[i];
}

那么你的unique list就是从0到lastIdx的数组结果位置(其余的用null填充;

关于基于Json文件的Java非重复数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46553121/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com