首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >第二个print语句是如何给出编译时错误的?

第二个print语句是如何给出编译时错误的?
EN

Stack Overflow用户
提问于 2018-06-10 00:26:28
回答 2查看 41关注 0票数 -4

第二个print语句给出了编译时错误。请解释一下

代码语言:javascript
复制
public class mainClass {
    public static void main(String args[]) {    
        final int a=10, b=20;

        while(a < b) {
            System.out.println("Hello");
        }
        System.out.println("World");
    } 
}
EN

回答 2

Stack Overflow用户

发布于 2018-06-10 00:28:33

条件a<b始终保持为真。

编译器检测到您的程序永远不会结束,并且永远不会到达第二个打印行,因此它抛出编译错误

您可能希望将您的while更改为if检查

票数 1
EN

Stack Overflow用户

发布于 2018-06-10 00:43:07

你的代码可以写成:

代码语言:javascript
复制
public class Answer {

    public static void main(String[] args) {

        while (10 < 20) { //always true, so loop is infinite
            System.out.println("Hello");
        }
        System.out.println("World"); //previous loop is infinite => this statement will never be reached
    }

}

但是,如果你这样写:

代码语言:javascript
复制
public class Answer {

    public static void main(String[] args) {

        int a = 10, b = 20;

        while (a < b) {

            System.out.println("Hello");
            b--; //if you decrease var b, in some point while condition becomes false
        }
        System.out.println("World"); //AND this statement will be reached
    }

}

请注意,int b不可能是最终的!

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50776306

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档