Java:条件初始化?

发布于 2024-08-30 19:53:32 字数 1884 浏览 6 评论 0原文

Ruby 有条件初始化。显然,Java 没有还是有?我尽量写得简洁一些,把范围限制得尽可能小。

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);

        }
}

错误

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

谜题

  1. 是否可以在 while 循环中为声明的值赋值? YES code1
  2. for 循环条件中的赋值? YES code2
  3. 条件初始化 NO
  4. 可以在循环中分配不同类型的值吗? 回复是
  5. 循环内初始化的一些规则?稍后声明外部来访问值,那么 init 呢? (?)

1.代码

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。代码

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!
        }
}

原始问题的一部分,具有多种不同类型的赋值和初始化——一行代码 100 行

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");}}

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");}}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

琉璃梦幻 2024-09-06 19:53:32

问题是变量可能没有在那里声明;变量可以在块内声明,但不能声明为表达式的一部分。但是,您可以在表达式中分配对象:

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

对于您的程序,以下内容更有意义:

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);
}

我还要补充一点,即使在您拥有它的地方允许声明,该变量也将属于 for 循环的范围,因此该变量在循环后将不再可见(超出范围)。

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).

婴鹅 2024-09-06 19:53:32

变量声明不能是表达式的一部分,它们是语句,如 Java 规范是这么说的

如果Java中存在条件初始化,那么如何判断变量是否被初始化呢?如何正确编译代码? (你需要了解Java编译器是如何工作的才知道这是不可能的)错误是如何处理的?有很多并发症。在代码中,即使变量被初始化,由于 Java 的作用域策略,它也会在 for 块之后消失。

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.

相守太难 2024-09-06 19:53:32

我认为您将赋值与声明混淆了。您可以将

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);
}

= 的运算符右关联,并将第一个参数设置为第二个参数并计算为第一个参数,因此类似于

a = b = c = 4

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

c 设置为 4、b 设置为 c(现在为 4)并将 a 设置为b(现在也是 4)

你的一行代码可以(为了清晰起见重新格式化)

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");}
     }
}

编辑 - (尽管这确实是丑陋的代码,如果你在我的项目中签入它,我会告诉你尽快重写它)

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)

虐人心 2024-09-06 19:53:32

Java条件初始化:

variable = (condition ? expression1 : expression2);

例如:

int max = (faces.length>curves.length ? faces.length : curves.length);

Java conditional initialization:

variable = (condition ? expression1 : expression2);

For example:

int max = (faces.length>curves.length ? faces.length : curves.length);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文