views:

166

answers:

3

Ruby has conditional initialization. Apparently, Java does not or does it? I try to write more succintly, to limit the range as small as possible.

import java.io.*;
import java.util.*;

public class InitFor{

        public static void main(String[] args){
                for(int i=7,k=999;i+((String h="hello").size())<10;i++){}

                System.out.println("It should be: hello = "+h);

        }
}

Errors

Press ENTER or type command to continue
InitFor.java:8: ')' expected
  for(int i=7,k=999;i+((String h="hello").size())<10;i++){}
                              ^

Puzzles

  1. Is it possible to assign a value to an declared value in while-loop? YES code1
  2. Assignment in for-loop conditional? YES code2
  3. conditional init NO
  4. Can you assign different types of values in loops? YES in a reply
  5. Some rule for initialization inside loops? Declare outside to access values later, what about init? (?)

1. CODE

import java.io.*;
import java.util.*;

public class InitFor{
        public static void main(String[] args){
                int k=5;
                while((k=(k%3)+1)!=1){
                        System.out.println(k);
                }
                //PRINTs only 3
        }
}

2. CODE

import java.io.*;
import java.util.*;

public class InitFor{

        public static void main(String[] args){
                int k=5;
                for(;(k=(k%3)+1)!=1;){
                        System.out.println(k);
                }
                //PRINTs only 3
                System.out.println(k); 
                // WHY DOES IT PRINT 1? Assign in for-loop!
        }
}

Part of the Original problem with many different kind of assignments and initializations -- 100lines of code in one-liner

for(int t=0,size=(File[] fs=((File f=f.getParentFile()).listFiles(filt))).size();fs==null;t++){if(t>maxDepth){throw new Exception("No dir to read");}}
+2  A: 

Variable declarations cannot be parts of expressions, they are statements, as the Java spec said so.

If conditional initialization existed in Java, then how to determine if a variable is initialized? How to compile the code properly? (you need to understand how do Java compiler work to know it is impossible) How are errors handled? There are many complications. In your code, even if the variable is initialized, it will be gone after the for block due to Java's scoping strategy.

SHiNKiROU
+5  A: 

The problem is that a variable may not be declared there; variables may be declared within a block, but may not be declared as part of an expression. However, you can allocate objects in an expression:

for(int i=7,k=999;i+((new String("hello")).length())<10;i++){}

For your program, the following would make more sense:

public static void main(String[] args){
    String h = "hello";
    for(int i=7,k=999;(i+h.length())<10;i++){} // not sure what this is doing
    System.out.println("It should be: hello = "+h);
}

I would also add that even if a declaration were allowed where you had it, the variable would belong to the scope of the for-loop, and so the variable would no longer be visible after the loop (out of the scope).

Michael Aaron Safyan
+2  A: 

I think you are confusing assignment with declaration. You could do

public static void main(String[] args){
    String h = null;
    for(int i=7,k=999;i+((h="hello").size())<10;i++){}

    System.out.println("It should be: hello = "+h);
}

the ='s operator is right associative and sets the first argument to the second argument and evaluates to the first argument, so something like

a = b = c = 4

is the same as

(a = (b = (c = 4)))

which sets c to 4, b to c (now 4) and a to b (now also 4)

your one line of code could be (reformatted for clarity)

File[] fs=null;                                                                            
File f= ??? ; //you never initialize f in the for loop, you need a starting value  
int t, size;                                                                               

for (t=0,size=(fs=((f=f.getParentFile()).listFiles(filt))).size();      
     fs==null;                                                                             
     t++) {
       if(t>maxDepth) {throw new Exception("No dir to read");}
     }
}

EDIT - (though that's really ugly code and if you checked it in on my project I'd be telling you to rewrite it ASAP)

aspo
KEY: assignment VS declarition: declaration not possible so I need "dummy vars", syntactic sugar, to declare first. Then, I can craft assignmetns. Accepted.
HH
side note, i feel it safer to initialize before loops. String does not but "File[]" seem to give err with unitialized value in for loop that tries assignment.
HH