Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Initialize multiple variables in for loop init?

Tags:

java

for-loop

I want to have two loop variables of different types. Is there any way to make this work?

@Override public T get(int index) throws IndexOutOfBoundsException {     // syntax error on first 'int'     for (Node<T> current = first, int currentIndex; current != null;              current = current.next, currentIndex++) {         if (currentIndex == index) {             return current.datum;         }     }     throw new IndexOutOfBoundsException(); } 
like image 312
Nick Heiner Avatar asked Aug 22 '10 18:08

Nick Heiner


People also ask

Can you initialize multiple variables in a for loop Java?

In Java, multiple variables can be initialized in the initialization block of for loop regardless of whether you use it in the loop or not.

How do I initialize more than one variable in a for loop?

Yes, I can declare multiple variables in a for-loop. And you, too, can now declare multiple variables, in a for-loop, as follows: Just separate the multiple variables in the initialization statement with commas. Do not forget to end the complete initialization statement with a semicolon.

Can we write multiple initialization statements in for loop?

No, you can only have one initializing statement.


2 Answers

The initialization of a for statement follows the rules for local variable declarations.

This would be legal (if silly):

for (int a = 0, b[] = { 1 }, c[][] = { { 1 }, { 2 } }; a < 10; a++) {   // something } 

But trying to declare the distinct Node and int types as you want is not legal for local variable declarations.

You can limit the scope of additional variables within methods by using a block like this:

{   int n = 0;   for (Object o = new Object();/* expr */;/* expr */) {     // do something   } } 

This ensures that you don't accidentally reuse the variable elsewhere in the method.

like image 172
McDowell Avatar answered Sep 20 '22 21:09

McDowell


You can't like this. Either you use multiple variables of the same type for(Object var1 = null, var2 = null; ...) or you extract the other variable and declare it before the for loop.

like image 28
Colin Hebert Avatar answered Sep 22 '22 21:09

Colin Hebert