简体   繁体   English

如何仅打印循环中的最后一个值

[英]How to print only last value from the loop

Currently console prints all the values from the loop, but there is needed to print only the last one当前控制台打印循环中的所有值,但只需要打印最后一个

public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int PeopleQty = scanner.nextInt();
        int PiecesQty = scanner.nextInt();
        int PizzaQty = 1;
        boolean divisibleByPieces = false;
        while (!divisibleByPieces) {
            System.out.println(PizzaQty);
            if ((PiecesQty * PizzaQty) % PeopleQty == 0)
                divisibleByPieces = true;
            ++PizzaQty;
        }
    }

Simply move the print statement after the loop:只需在循环后移动 print 语句:

while (!divisibleByPieces) {
    if ((PiecesQty * PizzaQty) % PeopleQty == 0) {
        divisibleByPieces = true;
        ++PizzaQty;
    }
}
System.out.println(PizzaQty);
while (!divisibleByPieces) {
           // System.out.println(PizzaQty); //move this print to outside of loop
            if ((PiecesQty * PizzaQty) % PeopleQty == 0)
                divisibleByPieces = true;
            ++PizzaQty;
        }
System.out.println(PizzaQty);

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

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