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. 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");}}
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).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With