繁体   English   中英

虽然while循环似乎没有循环-循环中只有数学

[英]This while loop doesn't seem to loop - there is only math in the loop

我不知道为什么我的循环不会继续。 每次我运行该程序时,它仅执行循环的一次迭代。

我正在实现基于数学家Lewis Caroll的算法,其中您从输入数字中删除最后一位数字,然后从剩余数​​字组成的数字中减去它。 例如,如果我输入数字48070,则输出为

48070
4807

它停在那里而不是继续。

// The "Divisible_Dianik" class.
import java.awt.*;

public class Divisible_Dianik
{

    public static void main (String[] args)
    {
        int userinput = 1;
        int lastint;
        int firstpart;
        int output = 1;

        while (output != 0)
        {
            userinput = In.getInt ();
            lastint = userinput % 10;
            firstpart = userinput / 10;
            output = firstpart - lastint;
            System.out.println (output);
            userinput = output;
        }

    } // main method
} // Divisible_Dianik class

我将假设In.getInt()是某种抽象,用于从用户那里获取基于终端的反馈。 它很容易被以下内容取代:

Scanner scan = new Scanner(System.in);
// in the loop
userinput = scan.nextInt();
scan.nextLine();

在这种情况下,您不循环的原因是由于每次输入都被阻塞。 你想要做的是移动的输入请求的循环之外

int lastint;
int firstpart;
int output = 1;
Scanner scan = new Scanner(System.in);
int userinput = scan.nextInt();
while (output != 0) {
    lastint = userinput % 10;
    firstpart = userinput / 10;
    output = firstpart - lastint;
    System.out.println(output);
    userinput = output;
}

暂无
暂无

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

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