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

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

Reading a value from String to String Array in Java

问题

以下是翻译好的部分:

如何在Java中将字符串读入字符串数组,我有以下代码:

  1. for (int i = 0; i <= jArr2.length(); i++) {
  2. JSONObject jArrOb = jArr2.getJSONObject(i);
  3. String empIDStr = jArrOb.getString("emp_id");
  4. String[] plant_ID[i] = empIDStr;
  5. }
  6. 编译器显示错误指出无法将字符串读入字符串数组我基本上是将JSON对象的值移动到字符串数组中
英文:

How to read a String into a String array in java , I have the following code :

  1. for (int i=0 ; i&lt;=jArr2.length() ; i++ ) {
  2. JSONObject jArrOb = jArr2.getJSONObject(i);
  3. String empIDStr = jArrOb.getString(&quot;emp_id&quot;);
  4. String[] plant_ID[i] = empIDStr;
  5. }

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

你需要在循环之前初始化字符串数组:

  1. int n = jArr2.length();
  2. String[] plant_ID = new String[n];
  3. for (int i = 0; i < n; i++)
  4. {
  5. JSONObject jArrOb = jArr2.getJSONObject(i);
  6. String empIDStr = jArrOb.getString("emp_id");
  7. plant_ID[i] = empIDStr;
  8. }
英文:

You need to initialize the String array before the loop:

  1. int n = jArr2.length();
  2. String[] plant_ID = new String[n];
  3. for (int i=0 ; i&lt;n ; i++ )
  4. {
  5. JSONObject jArrOb = jArr2.getJSONObject(i);
  6. String empIDStr = jArrOb.getString(&quot;emp_id&quot;);
  7. plant_ID[i] = empIDStr;
  8. }

答案2

得分: 0

请尝试以下操作,您首先需要创建数组。
确保更改for循环的上限,以避免数组越界异常。

  1. String[] plant_ids = new String[jArr2.length];
  2. for (int i=0; i<jArr2.length(); i++ ) {
  3. JSONObject jArrOb = jArr2.getJSONObject(i);
  4. String empIDStr = jArrOb.getString("emp_id");
  5. plant_ids[i] = empIDStr;
  6. }
英文:

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.

  1. String[] plant_ids = new String[jArr2.length];
  2. for (int i=0; i&lt;jArr2.length(); i++ ) {
  3. JSONObject jArrOb = jArr2.getJSONObject(i);
  4. String empIDStr = jArrOb.getString(&quot;emp_id&quot;);
  5. plant_ids[i] = empIDStr;
  6. }

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:

确定