【问题标题】:Access certain location in array of strings访问字符串数组中的某个位置
【发布时间】:2014-05-12 03:30:24
【问题描述】:

我想在数组中输入 3 个名称。然后我想访问第二个名字中第二个字符的位置。

首先,我在第 13 行遇到了一个越​​界异常。另外,我知道的第二个 for 循环完全关闭,请原谅。

为什么会出现异常以及如何访问某些字符串中的某些字符位置?

class Names
{
    public static void main(String[]args)
    {
        int index;
        String names[];
        names = new String [3];

        for(index = 1; index <= names.length; index++)
            {
                System.out.println("Enter name " + index);
                names[index] = EasyIn.getString();
            }
        for(index = 0; index < names.length; index++)
            {
                System.out.println(names[1][2]);
            }
    }
}

【问题讨论】:

标签: java arrays


【解决方案1】:

几件事。

您可以像String[] names = new String[3] 一样一次性制作String 对象中的array

在您的第一个循环中,您可以这样开始:

for(index = 1; index <= names.length; index++)

这是错误的,除非您想跳过第一个元素,否则您的索引从 0 开始。然后你定义index &lt;= names.length;,这也是错误的。长度返回实际长度,但我们现在知道 array 从 0 开始。您应该像这样定义它:

for(index = 0; index < names.length; index++)

正如其他人之前所说,如果你想从字符串中获取某个字符,你可以使用 `myString.charAt()',所以在你的情况下,你应该这样写:

System.out.println(names[<an index>].charAt(2));

【讨论】:

    【解决方案2】:

    您的代码应如下所示:

            int index;
            String names[];
            names = new String [3];
    
            for(index = 0; index < names.length; index++)
            {
                System.out.println("Enter name " + index);
                names[index] = EasyIn.getString();
            }
            for(index = 0; index < names.length; index++)
            {
                if (names[index] != null && names[index].length() > 2)
                    System.out.println(names[index].charAt(2));
            }
    

    【讨论】:

    • 好的,还有一件事。这只允许我输入 2 个名字。一旦我输入 2 个名称,它会立即跳到第二个 for 循环,而不允许我输入第三个名称。
    • 我不知道你的“EasyIn.getSrig()”函数在做什么,但肯定是被调用了3次。您应该会看到输出。
    【解决方案3】:

    您可以创建静态数组并从中读取值

    String[] array = {"Peter", "John", "Andre"}; //now you have three items in array
    char secondChar = array[1].charAt(1); //first get second element, than get second char from it
    

    所以现在secondCharo - 还要记住数组从0 开始所以这就是为什么索引1 表示数组中的第二项 - 同样适用于charAt,字符串基本上只是字符数组.

    【讨论】:

      【解决方案4】:

      试试这个:

      在你的第一个循环中:

      for(index = 0; index < names.length; index++)
      

      删除你的第二个循环,因为不想显示每个元素,你可以直接这样做:

      System.out.println(names[1].charAt(1));
      

      【讨论】:

        【解决方案5】:

        如果要访问字符串中的某个字符,请使用mystring.charAt(index)

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2016-08-04
          • 2011-02-12
          • 1970-01-01
          • 2016-07-10
          • 2012-02-18
          • 1970-01-01
          • 1970-01-01
          • 2012-06-22
          相关资源
          最近更新 更多