The better question might be: Why wouldn't you want to use a FOR loop to iterate through an array? There are many ways to iterate through an Array or a collection and there is no law that states you have to use the FOR loop. In a lot of cases, it's simply the best to use for speed, ease of use, and readability. And yet, in other cases it is not:
The Array:
int[] array = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
Display Array with the typical for loop:
for (int i = 0; i < array.length; i++) {
System.out.println(array[i]);
}
Display Array with the enhanced for loop:
for(Integer num : array) {
System.out.println(num);
}
Display Array with the do/while loop:
int i = 0;
do {
System.out.println(array[i++]);
} while (i < array.length);
Display Array with the while loop:
int j = 0;
while (j < array.length) {
System.out.println(array[j++]);
}
Display Array through Recursive Iteration:
iterateArray(array, 0); // 0 is the start index.
// The 'iterateArray()' method:
private static int iterateArray(int[] array, int index) {
System.out.println(array[index]);
index++;
if (index == array.length) {
return 0;
}
return iterateArray(array,index);
}
Display Array using Arrays.stream() (Java8+):
Arrays.stream(array).forEach(e->System.out.print(e + System.lineSeparator()));
Display Array using IntStream (Java8+):
IntStream.range(0, array.length).mapToObj(index -> array[index]).forEach(System.out::println);
Choose your desired weapon....
Answer from DevilsHnd - 退した on Stack OverflowThe better question might be: Why wouldn't you want to use a FOR loop to iterate through an array? There are many ways to iterate through an Array or a collection and there is no law that states you have to use the FOR loop. In a lot of cases, it's simply the best to use for speed, ease of use, and readability. And yet, in other cases it is not:
The Array:
int[] array = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
Display Array with the typical for loop:
for (int i = 0; i < array.length; i++) {
System.out.println(array[i]);
}
Display Array with the enhanced for loop:
for(Integer num : array) {
System.out.println(num);
}
Display Array with the do/while loop:
int i = 0;
do {
System.out.println(array[i++]);
} while (i < array.length);
Display Array with the while loop:
int j = 0;
while (j < array.length) {
System.out.println(array[j++]);
}
Display Array through Recursive Iteration:
iterateArray(array, 0); // 0 is the start index.
// The 'iterateArray()' method:
private static int iterateArray(int[] array, int index) {
System.out.println(array[index]);
index++;
if (index == array.length) {
return 0;
}
return iterateArray(array,index);
}
Display Array using Arrays.stream() (Java8+):
Arrays.stream(array).forEach(e->System.out.print(e + System.lineSeparator()));
Display Array using IntStream (Java8+):
IntStream.range(0, array.length).mapToObj(index -> array[index]).forEach(System.out::println);
Choose your desired weapon....
Considering you have an array like :
int[] array = {1,2,4,5,6};
You can use stream to iterate over it, apart from printing you can perform lot many thing over this array.
Arrays.stream(array).forEach(System.out::println);
Similarly you can do lot many action over collections as well:
List<String> myList = new ArrayList<>(); List
myList.add("A");
myList.add("B");
Stream.of(myList).forEach(System.out::println);
myList.forEach(System.out::println);
Struggling with Arrays and loops
Why is it a matrix rather than a 1D array? It has a width of 1, so it is linear. Do you want to add more students to the same grade? Then width should be more than 1 (or grow as you add students).
You can put fullname into the correct place in your array without conditionals using:
currentGrade[studentAge - 5] = fullName; //check for valid input, first.
More on reddit.comcreate new array inside loop? - Processing Forum
Java array/for loop
For-each loop ArrayList
Videos
I'm relatively new to java and up until this point aside from a few 'normal' speed bumps, I've had a good grasp on the content we've been learning. However we're doing arrays now and the course content doesn't cover input, if else statements that assign strings to arrarys, or much other than the basics of 'int' 1D and 2D arrays.
I have to store a 'name' into a 'grade'. I've initialized all my variables as you can see, and the code blocks that aren't commented out work exactly as they're supposed to but I don't know if I'm on the right track with my logic or if 2D arrays are the right ones to use and then how to apply them appropriately?
Edited: Format
Code:
static void enrolMethod(){
Scanner input = new Scanner(System.in);
String[][] currentGrade = new String [1][10];
currentGrade[0][0] = "Grade_Prep:";
currentGrade[1][0] = "Grade_1:";
currentGrade[2][0] = "Grade_2:";
currentGrade[3][0] = "Grade_3:";
currentGrade[4][0] = "Grade_4:";
currentGrade[5][0] = "Grade_5:";
currentGrade[6][0] = "Grade_6:";
String firstName;
String n1;
String lastName;
String n2;
String fullName;
int studentAge;
String enrolAgain;
System.out.println("Enter child's first name:");
firstName = input.nextLine();
n1 = firstName.substring(0,1).toUpperCase() + firstName.substring(1);
System.out.println("Enter child's surname:");
lastName = input.nextLine();
n2 = lastName.substring(0,1).toUpperCase() + lastName.substring(1);
fullName = (n1 + "_" + n2);
System.out.println("Enter child's age");
studentAge = input.nextInt();
// //IF STATEMENTS FOR AGE HERE
// if (studentAge == 5) {
// currentGrade[0][0] = fullName;
// } else if (studentAge == 6) {
// currentGrade[1][0] = fullName;
// } else if (studentAge == 7) {
// currentGrade[2][0] = fullName;
// } else if (studentAge == 8) {
// currentGrade[3][0] = fullName;
// } else if (studentAge == 9) {
// currentGrade[4][0] = fullName;
// } else if (studentAge == 10) {
// currentGrade[5][0] = fullName;
// } else if (studentAge == 11) {
// currentGrade[6][0] = fullName;
// } else {
// System.out.println("Invalid input. Please Try Again!");
// enrolMethod();
// }
//STORE TO ARRAY HERE???
System.out.println("This child has been successfully enrolled: " + fullName);
System.out.println("Do you want to enrol another child? Y/N");
enrolAgain = input.next();
if (enrolAgain.equalsIgnoreCase("y")) {
enrolMethod();
} else if (enrolAgain.equalsIgnoreCase("n")) {
menuSelect();
}
}
Why is it a matrix rather than a 1D array? It has a width of 1, so it is linear. Do you want to add more students to the same grade? Then width should be more than 1 (or grow as you add students).
You can put fullname into the correct place in your array without conditionals using:
currentGrade[studentAge - 5] = fullName; //check for valid input, first.
In a 2D array, the first set of brackets denotes the row. The second set of brackets denotes the column. array[row][column]. In your case, each grade is a row, and each student is a column within its respective row.
When you initialized your array with = new String[1][10], you created an array with one row consisting of 10 columns. It would look something like this:
Grade_Prep: {Student1, Student2, ..., Student10}
You want a row for each grade, so increase the number of rows in your array initialization.
Visualizing your array can help you understand how you need to access it.