【问题标题】:Transform a doWhile in a While loop在 While 循环中转换 do While
【发布时间】:2016-11-20 20:06:56
【问题描述】:

我的任务有问题。我必须将下面的 doWhile 循环转换为 While 循环,以便两个循环的结果相同? 如您所见,Integer 类型只是在 doWhile 循环中。但是int 类型之间有什么区别。我该如何解决这个任务?

doWhile 循环:

public Integer a_doWhile(int x){
    int i = 0;
    Integer result;
    do {
        result = ++i*i;
    } while (result < x);
    return result;
}

我的解决方案:

public Integer a_while(int x){
    int i=0;
    int result;
    while(result < x){
        result = ++i*i;
    return result;
    }
}

但我的解决方案是错误的。它与这个“整数”有关,有人可以帮帮我吗?谢谢:)

【问题讨论】:

    标签: java class loops integer


    【解决方案1】:

    int 和 Integer 是同一事物的不同表示。 Int 是原始的,而 Integer 是对象表示。这里讨论What is the difference between an int and an Integer in Java and C#?

    您可以像这样将 dowhile 转换为 while

    public Integer a_While(int x){
        int i = 0;
        Integer result = ++i*i;
        while (result < x) {
            result = ++i*i;
        }
        return result;
    

    【讨论】:

    • 工作就像一个魅力。非常感谢Leadfoot!
    猜你喜欢
    • 2015-02-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-22
    • 2018-11-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多