如何从循环中只打印最后一个值



当前控制台打印循环中的所有值,但只需要打印最后一个

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;
}
}

只需将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);

最新更新