Reputation: 5013
I want to loop through an array and print any values that are not null, here is the code I am trying to use:
for (int i = 0; i < 10; i++) {
if (studentNamesArray[i] != null) {
studentFound = true;
System.out.println("Which student would you like to delete?");
System.out.println(i + ": " + studentNamesArray[i]);
int studentChoice = input.nextInt();
}
}
Array:
static String[] studentNamesArray = new String[10];
The problem is that it is only printing out index[0]
. How can I fix this?
EDIT:
Here is my full code:
static void deleteStudent() {
boolean studentFound = false;
for (int i = 0; i < 10; i++) {
if (studentNamesArray[i] != null) {
studentFound = true;
System.out.println("Which student would you like to delete?");
System.out.println(i + ": " + studentNamesArray[i]);
}
int studentChoice = input.nextInt();
for (i = 0; i < 10; i++) {
for (i = studentChoice + 1; i < studentNamesArray.length; i++) {
studentNamesArray[i - 1] = studentNamesArray[i];
}
nameArrayCount = nameArrayCount - 1;
studentNamesArray[studentNamesArray.length - 1] = null;
for (i = studentChoice + 1; i < 9; i++) {
for (int y = 0; y < 3; y++) {
studentMarksArray[i - 1][y] = studentMarksArray[i][y];
}
}
markArrayCount = markArrayCount - 1;
for (int y = 0; y < 3; y++) {
studentMarksArray[9][y] = 0;
}
}
}
if (!studentFound) {
System.out.println("There are no students stored");
}
}
Upvotes: 2
Views: 2485
Reputation: 6887
Use the for-loop only to print the students names. And read the studentChoice
once after you printed all the students. Otherwise it waits for input after printing the studentNamesArray[0]
System.out.println("Which student would you like to delete?");
for (int i = 0; i < 10; i++) {
if (studentNamesArray[i] != null) {
studentFound = true;
System.out.println(i + ": " + studentNamesArray[i]);
}
}
int studentChoice = input.nextInt();
Upvotes: 4
Reputation: 35547
Only reason I can see here, other elements should be null
. You can make sure it as follows
for (int i = 0; i < 10; i++) {
if (studentNamesArray[i] != null) {
studentFound = true;
System.out.println("Which student would you like to delete?");
System.out.println(i + ": " + studentNamesArray[i]);
int studentChoice = input.nextInt();// you need to check this
}else{
System.out.println(i + ": " + studentNamesArray[i]);
}
}
But may be there is another reason. If input.nextInt()
is take from Scanner
, your program will wait there for a user input. Then you have to provide that input to continue. Make sure those things.
Upvotes: 1
Reputation: 8246
Make sure that the contents of the array are not null, or they wont print out
Upvotes: 1