数组和数组列表

时间:2014-03-07 23:14:05

标签: java arrays

我的大部分程序已经完成,但它不能正常工作,而且我已经盯着它看了一段时间,我无法理解它。有人能帮助我注意我做错了什么吗?我不是要求别人修理它,而是解释它。

  
      
  1. 使用main方法创建一个名为CustomerLister1的类,该方法实例化一个名为customerName的String对象数组。该   数组应该有七个String对象的空间。分配每个   跟随字符串到数组中的连续位置开始于   数组索引0。

    Chris
    Lois
    Meg
    Peter
    Stewie
    
         

    编写增强的for循环以显示名称数组。最后两个数组元素显示的内容是什么?为什么这么值?

         

    将字符串“Meg”和“Brian”分别添加到索引3和4中,以便该数组包含以下元素:

    Chris
    Lois
    Meg
    Meg
    Brian
    Peter
    Stewie
    
         

    编写增强的for循环以显示名称数组。

         

    写第二个传统的for循环,检查字符串“Meg”的每个元素,如果在数组中找到,删除它,移动   剩余的元素,并显示名称数组。两者都是   从阵列中正确删除“Meg”的实例?

  2.   
  3. 为第二个名为CustomerLister2的类修改您编写第1部分的代码,以便使用ArrayList而不是数组   将名称存储为String对象。

         

    如前所述添加五个名称,然后添加“Brian”以便它   是ArrayList中的第四个名称。现在将“Meg”添加到第三个   列表中的位置(将有两个相同的字符串“Meg”   列表)。

         

    使用增强的for循环显示所有String对象,如   部分#1并使用传统的for循环删除“Meg”并显示   修订过的ArrayList。再一次,“梅格”完全被移除了   列出?

  4.   
public class CustomerLister1
 {
  public static void main(String[] args)
  {
   String[] customerName = new String[7];
   customerName[0] = "Chris";
   customerName[1] = "Lois";
   customerName[2] = "Meg";
   customerName[3] = "Peter";
   customerName[4] = "Stewie";

   for (int i = customerName.length-1; i > 3; i--)
    {
      customerName[i] = customerName[i - 2];
    }
     customerName[3] = "Meg";
     customerName[4] = "Brian";


   for (int m = 0; m <= customerName.length-1; m++)
    {
     if (customerName[m].equals("Meg"))
      {
       for (int j = m; j < customerName.length; j++)
        {
         if (j < customerName.length-2)
         {
         customerName[j] = customerName[j+1];
        } else { 
           customerName[j] = "";
          }
         }
         m++;
        }
        for (String element : customerName)
        {
         System.out.println(element);
        }
        }
       }
     }

2 个答案:

答案 0 :(得分:0)

许多输出的问题很明显,因为你的“增强”循环中有你的打印循环,无论这意味着什么。

除此之外,您应该在最里面的循环中使用&lt; =,因为您还想移动最后一个元素。

答案 1 :(得分:0)

首先,&#34;增强&#34;循环(我认为)是for-each循环。它在java中看起来像这样。

for (String name : customerName) {
     System.out.println(name);
}

而传统的for循环是迭代,这就是你正在做的事情。

for (int i = 0; i < num; i++) {
     System.out.println(customerName[i]);
}

您输出的输出太多主要是因为您的上一个for循环嵌入太远了。让我增加制表位以使其更明显。

for (int m = 0; m <= customerName.length-1; m++)
{
     if (customerName[m].equals("Meg"))
     {
           for (int j = m; j < customerName.length; j++)
           {
                 if (j < customerName.length-2)
                 {
                        customerName[j] = customerName[j+1];
                 } else { 
                        customerName[j] = "";
                 }
           }
           m++;
       }
       for (String element : customerName)
       {
            System.out.println(element);
       }
 }

你看到你的最后一个for循环嵌入你的第一个吗?这意味着每次第一个for循环for (int m = 0; m <= customerName.length-1; m++)运行时,最后一个for循环也将运行。这意味着整个循环运行了m次。

对于数学解释,LoopA运行n次。 LoopB运行了m次。如果LoopB位于LoopA内,则LoopB将总共运行n * m次。