从String读取值转换为String Array在Java中

huangapple go评论69阅读模式
英文:

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&lt;=jArr2.length() ; i++ ) {
    JSONObject jArrOb = jArr2.getJSONObject(i);
    String empIDStr = jArrOb.getString(&quot;emp_id&quot;);
    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&lt;n ; i++ )
{
     JSONObject jArrOb = jArr2.getJSONObject(i);
     String empIDStr = jArrOb.getString(&quot;emp_id&quot;);
     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&lt;jArr2.length(); i++ ) {
   JSONObject jArrOb = jArr2.getJSONObject(i);
   String empIDStr = jArrOb.getString(&quot;emp_id&quot;);
   plant_ids[i] = empIDStr;             
}      

huangapple
  • 本文由 发表于 2020年10月13日 22:25:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/64337146.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定