英文:
Reading a value from String to String Array in Java
问题
以下是翻译好的部分:
如何在Java中将字符串读入字符串数组,我有以下代码:
for (int i = 0; i <= jArr2.length(); i++) {
JSONObject jArrOb = jArr2.getJSONObject(i);
String empIDStr = jArrOb.getString("emp_id");
String[] plant_ID[i] = empIDStr;
}
编译器显示错误,指出无法将字符串读入字符串数组。我基本上是将JSON对象的值移动到字符串数组中。
英文:
How to read a String into a String array in java , I have the following code :
for (int i=0 ; i<=jArr2.length() ; i++ ) {
JSONObject jArrOb = jArr2.getJSONObject(i);
String empIDStr = jArrOb.getString("emp_id");
String[] plant_ID[i] = empIDStr;
}
The compiler shows an error stating that String cannot be read into String Array. I am basically moving the values of JSON object into a String Array.
答案1
得分: 2
你需要在循环之前初始化字符串数组:
int n = jArr2.length();
String[] plant_ID = new String[n];
for (int i = 0; i < n; i++)
{
JSONObject jArrOb = jArr2.getJSONObject(i);
String empIDStr = jArrOb.getString("emp_id");
plant_ID[i] = empIDStr;
}
英文:
You need to initialize the String array before the loop:
int n = jArr2.length();
String[] plant_ID = new String[n];
for (int i=0 ; i<n ; i++ )
{
JSONObject jArrOb = jArr2.getJSONObject(i);
String empIDStr = jArrOb.getString("emp_id");
plant_ID[i] = empIDStr;
}
答案2
得分: 0
请尝试以下操作,您首先需要创建数组。
确保更改for循环的上限,以避免数组越界异常。
String[] plant_ids = new String[jArr2.length];
for (int i=0; i<jArr2.length(); i++ ) {
JSONObject jArrOb = jArr2.getJSONObject(i);
String empIDStr = jArrOb.getString("emp_id");
plant_ids[i] = empIDStr;
}
英文:
Try the following where you create the array first.
Make sure to change the upper bound of your for loop to avoid an Array out of bounds exception.
String[] plant_ids = new String[jArr2.length];
for (int i=0; i<jArr2.length(); i++ ) {
JSONObject jArrOb = jArr2.getJSONObject(i);
String empIDStr = jArrOb.getString("emp_id");
plant_ids[i] = empIDStr;
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论