Home > Back-end >  How to print only last value from the loop
How to print only last value from the loop

Time:06-16

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

CodePudding user response:

Simply move the print statement after the loop:

while (!divisibleByPieces) {
    if ((PiecesQty * PizzaQty) % PeopleQty == 0) {
        divisibleByPieces = true;
          PizzaQty;
    }
}
System.out.println(PizzaQty);

CodePudding user response:

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

CodePudding user response:

you can reach your goal like that :

public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int PeopleQty = scanner.nextInt();
        int PiecesQty = scanner.nextInt();
        int PizzaQty = 1;
        while (true) {
            if ((PiecesQty * PizzaQty) % PeopleQty == 0)
                break;
              PizzaQty;
        }
        System.out.println(PizzaQty);
    }
  •  Tags:  
  • java
  • Related