简体   繁体   English

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

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

I can not figure out why my loop won't continue. 我不知道为什么我的循环不会继续。 Every time I run the program, it executes only one iteration of the loop. 每次我运行该程序时,它仅执行循环的一次迭代。

I am implementing the algorithm based on mathematician Lewis Caroll where you remove the last digit from an input number and subtract it from the number formed by the remaining digits. 我正在实现基于数学家Lewis Caroll的算法,其中您从输入数字中删除最后一位数字,然后从剩余数​​字组成的数字中减去它。 For example, if I input the number 48070 the output is 例如,如果我输入数字48070,则输出为

48070
4807

and it stops there instead of continuing. 它停在那里而不是继续。

// 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

I'm going to assume that In.getInt() is some kind of abstraction for getting terminal-based feedback from the user. 我将假设In.getInt()是某种抽象,用于从用户那里获取基于终端的反馈。 It's easily supplanted by this: 它很容易被以下内容取代:

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

If this is the case, the reason you don't loop is due to this blocking for input every time. 在这种情况下,您不循环的原因是由于每次输入都被阻塞。 What you want to do is move the request for input outside of the loop. 你想要做的是移动的输入请求的循环之外

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