Reputation: 15
I would like to know if the following code would increase the array value to the next array value every time it runs.
For e.g, on the first run, it stores value in count[1]
of the array,
on the next run does it store the value in count[2]
?
public static void getadminName(){
String[] name= new String[20];
for (int count=0;count<name.length;count++){
name[count]= JOptionPane.showInputDialog(null,"Please enter
admin's name:");
String scount=Integer.toString(count);
name[count]= scount+1;
break;
}
}
Upvotes: 1
Views: 106
Reputation: 24691
Remove the break
statement and the code should do approximately what you want it to. Keep in mind that name
is an array of strings, with twenty elements. When you do name[count]
, you're referring to the count
th element of that array, which is a String.
You notice that the for
loop has three parts:
int count=0;
declares an integer named 'count', initialized to the value 0.count < name.length
declares a "termination condition" - if, before executing the code inside the loop, this condition is false, then the loop ends. In this case, it runs until the variable count
has a value greater than the length of the array name
.count++
is executed immediately after each iteration of the loop finishes. The sum, in this case, is that you start with count=0
, accessing the first element of name
, and then you do things in the loop, and then count
increases by one, and the code inside the loop runs again, until count
is greater than the length of name
.
The statement break
specifically jumps out of the loop, regardless of whether it otherwise would have. That's what you don't want to do here - you want to continue looping.
Upvotes: 3