Structure of a cycle for(){}
in java:
In code:
for(inicialización;condicion;incremento)
{
//instrucciones
}
1)
Execution of the for control structure begins with the
initialization instruction. This instruction usually performs the
initialization of a control variable that is usually known as
sentinel .
2)
Next we check the condition whose result has to be
a Boolean value of true or false.
3)
If the condition evaluates to true, the block is executed
instructions delimited by the keys that are only necessary if
There is more than one instruction.
4)
Then the increment instruction is executed and checked again
the condition. So on until the condition is not met.
In your case:
We ask for a digit.
System.out.println("Introduzca los digitos para la sucesion1");
We prepare a for to travel x data:
for(char digito:){
}
In our case when doing for (char: digit) we will read each character that compose the string that is saved in digit.
Here there is :
, these two points indicate what the value of
the initialization (remember the shape of a for).
for(char digito: q.nextLine()){
}
q
will be our data scanner and nextLine()
will return all the string read to the next line, that is:
"Hi, I'm pepe" will be saved completely, unlike using next()
that only
Save up to the "Hello, I'm pepe" - > "Hello."
We continue, now that saved string will apply toCharArray()
, this function converts that string into an array of characters.
for(char digito: q.nextLine().toCharArray()){
}
Then we are saying: "For each character contained in the nextline()
scanner, do what is between the two keys."
How does the for to work without having incremental or conditional?: In the for cycle, initialization, condition and increment are optional instructions, but this has an initializer that is an array , which forces the for
to go through each of the letters that make up that array.
Next we add to seq1
the character that is in the iteration of the (I assume it is an array)
for (char digito : q.nextLine().toCharArray()) {
seq1.add(digito - '0');
}
Translating all the for: For each character of the character array obtained from the scanner that requested the user's digit, add it to the array seq1
Now, for your question:
Yes and no, after the initialization you can add any "condition", taking into account that you must use logical operators like &&(and)
and ||(or)
and respecting the basic structure:
for(inicializacion ; aqui || tus && condiciones ; contador){}
As for the actions, they will go in the code block, not in the body of for
, that is:
for(int i=0; i<a || i<b || i>c; i++){
// AQUI
int x = i + 100;
int z = i x 2;
}
Examples:
for (int i = 1, j = 100; i <= 100 && j > 0; i = i - 1 , j = j-1) {
System.out.println("Inside For Loop");
}
for( int i = 0 ; i < 100 || otraCondicion() ; i++ ) {
System.out.printLn("Inside another For Loop");
}