Reputation: 67
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);
}}
Upvotes: 1
Views: 145
Reputation: 174
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);)
Upvotes: 0
Reputation: 51
for(int i=0;i<=2;i++){
System.out.println(C[i]);
}
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);
}
Upvotes: 0
Reputation: 3180
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);
Upvotes: 0
Reputation: 11740
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.)
Upvotes: 1