简体   繁体   English

while语句如何工作?

[英]How does this while statement work?

I have an echo text Java code. 我有一个回显文本Java代码。 I can't understand one of the statements? 我不明白其中一种说法? The code is:- 代码是:-

public class testing {

public static void main(String[] args) {
    boolean isRedirect = false;
    if(args.length != 0){
        isRedirect = true;
    }
    int ch;
    try{
        while ((ch = System.in.read()) != ((isRedirect) ? -1 : '\n'))
        System.out.print((char) ch);
    }
    catch(java.io.IOException ioe){
        System.err.println("I/O Error");
    }
    System.out.println();
}
}

I know the code creates a Boolean to check whether the input is coming or not. 我知道代码创建了一个布尔值来检查输入是否到来。 I know the while loop is outputting integers that '(char)' is converting to characters but I don't understand how the while statement does this. 我知道while循环输出的是'(char)'转换为字符的整数,但是我不明白while语句是如何做到这一点的。 Thanks in advance. 提前致谢。

while ((ch = System.in.read()) != ((isRedirect) ? -1 : '\n'))

has the same effect as: 具有与以下相同的效果:

do {
    ch = System.in.read();
} while(ch != (isRedirect ? -1 : '\n'));

which has the same effect as: 具有与以下相同的效果:

if(isRedirect) {
    do {
        ch = System.in.read();
    } while(ch != -1);

} else {

    do {
        ch = System.in.read();
    } while(ch != '\n');
}

which is hopefully understandable. 希望可以理解。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM