This is for class homework. She is making us use array and array list in two parts. Basically she is showing us how using arraylist is alot easier than arrays.
I am having alot of trouble getting the array part to work.
Create a class called CustomerLister1 with a main method that instantiates an array of String objects called customerName. The array
should have room for six String objects. Use an initializer list to
put the following names into the array:Chris Lois Meg Peter StewieWrite an enhanced for loop to display the array of names. What is displayed for the last array element? Why is it that value?
Add the Strings “Meg” and “Brian” into index 3, and 4, respectively, so that the array contains the following elements:
Chris Lois Meg Meg Brian Peter StewieWrite an enhanced for loop to display the array of names.
Write a second, traditional for loop that checks each element for the String “Meg”, if found in the array, remove it, shift the
remaining elements, and display the array of names. Are both instances
of “Meg” removed correctly from the array?
This is my code
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+1;j < customerName.length-1;j++)
{
customerName[j]= customerName[j-1];
}
}
}
for (String element : customerName)
{
System.out.println(element);
}
}
}
I have tried messing with the element position. It won’t print right because I have meg back to back and it replaces the first meg with the second meg. What can i do here?
Change your if statement like this:
By decrementing i by 1, you’ll hit the same index again.
And also AmitD is correct; you need customerName[j+1], not [j-1].
Oh, and you’ll need to handle the end of the array properly; don’t want to try and set customerName[6] = customerName[7] when there is no customerName[7].
Edit: Ah, you’ll need to start j at m, not m+1. That way you remove the “Meg” at customerName[m] as well as moving everything ahead of it backwards.
Edit: And the while part of the loop was skipping the last element in the array.