【问题标题】:String[] array taking items out individuallyString[] 数组单独取出项目
【发布时间】:2025-11-23 06:20:02
【问题描述】:

我有一个方法需要 String[] 来获取一些细节,但是在将这些细节放入之后我如何将它们一一取出?

new String[] otherDetails = {"100", "100", "This is a picture"};

现在在图片中我想将第一个字符串设置为高度,第二个作为宽度,第三个作为描述。

【问题讨论】:

  • 我们真的需要三个相同的答案吗?
  • @Steve 绝对不是。但它似乎经常发生在非常简单的问题上。

标签: java arrays string split


【解决方案1】:

您通过索引引用数组的元素,如下所示:

height = otherDetails[0]; // 100
width = otherDetails[1]; // 100
description = otherDetails[2]; // This is a picture

【讨论】:

  • 数组索引从 0 开始并转到 Array.size - 1 也毫无价值,这至少是我使用过的所有编程语言的标准。
【解决方案2】:

您使用索引来获取值

height = otherDetails[0];
width = otherDetails[1];
description = otherDetails[2];

【讨论】:

    【解决方案3】:

    从数组中提取详细信息如下:

    height = otherDetails[0]; // 100
     width = otherDetails[1]; // 100
     description = otherDetails[2]; // This is a picture
    

    然后调用你的方法MyFunction(String heigth,String width,String description);

    【讨论】:

    • 你为什么发布与其他两个相同的答案?
    【解决方案4】:

    索引 cmets 可能是您要查找的内容,但您也可以使用循环遍历元素。

    int arraySize = stringArray.length;
    for(int i=0; i<arraySize; i++){
        if(i==0)
            height = stringArray[i];  //do stuff with that index
    }
    

    对于您的特定问题,这不是“正确”的方法,但我认为它可能会帮助您了解访问数组内项目的方式。

    旁注,您可以使用替代语法:

    String[] array = new String[3];
    //fill in array
    for(String s : array){
        //this cycles through each element which is available as "s"
    }
    

    【讨论】: