1

I'm trying to populate an array [C], then display it using a for loop.. I'm new to arrays and this is confusing the hell out of me, any advice is appreciated!

Below is my code:

public static void main(String[] args) {

    int A[] = new int[5];
    int B[] = new int[5];
    String C[] = new String[5];
    int D[] = new int[5];

    C[] = {"John", "Cook", "Fred"};
    for(String name: C)
        System.out.println(C);
    }}
3
  • 2
    so what is your particular question? Commented Mar 14, 2015 at 18:50
  • Basically, I've got to populate array 'C' then display it using a for-loop Commented Mar 14, 2015 at 18:51
  • Think about what you're trying to do with your current loop. The foreach loop works as: for each item in iterable. You're printing out the iterable for each item, not the item itself (name). Commented Mar 14, 2015 at 19:04

5 Answers 5

1

You can define and populate an array in two ways. Using literals:

    String c[] = {"John", "Cook", "Fred"};
    for(String name : c) { // don't forget this { brace here!
        System.out.println(name); // you want to print name, not c!
    }

Or by setting each index element:

    int d[] = new int[2];
    d[0] = 2;
    d[1] = 3;
    for(int num: d) {
        System.out.println(num);
    }

(You can only use the literal when you first define the statement, so

    String c[];
    c = {"John", "Cook", "Fred"};

Will cause an "illegal start of expression" error.)

Sign up to request clarification or add additional context in comments.

1 Comment

What works? Which variables? And do you mean static? Java doesn't have a global keyword.
0

You want to print name instead of C.

Comments

0

C is the name of the array, while name is the name of the String variable. Therefore you must print name instead of C

   System.out.println(name);

Comments

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

here 2 is the last index of the array C

You cannot simply print an array you have to provide an index to your item

where C[0] is john and C[1] is Cook and so on

and if you want to use a for each loop then this is how it goes

for(Iterator<String> i = someList.iterator(); i.hasNext(); ) {
    String item = i.next();
    System.out.println(item);
} 

Comments

0

Try specifying at what index you want to add the element.

Example:

C[0] = "hej";

Also, print the element in the array, not the actual array. (System.out.println(name);)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.