Home > OS >  How can i do while loop with scanner numbers up to 100 and their sum also will not be over 100
How can i do while loop with scanner numbers up to 100 and their sum also will not be over 100

Time:10-12

    Scanner scanner = new Scanner(System.in);
        System.out.println("Enter number");

        int input  = 0;
        int sum = 0;

        while (input != 100)
        {
            input  = scanner.nextInt();
            if ((input   sum) > 100)
                break;
            sum = sum   input ;

        }

        System.out.println("Sum of Numbers : "   sum);
    }

Hello,i have a task, it asks us; Write a program that asks user to enter a number If number is less than 100, then ask user to enter another number and find sum of entered 2 numbers. Keep asking user to enter numbers until the sum of all entered numbers is at least 100. If first number entered by user more than or equal to 100, print message “This number is already more than 100” and do not ask user to enter any other numbers.

I can print the sum of numbers entered by user but i just can't stop it. Eventho i do with break it breaks after 100. number.

CodePudding user response:

This problem can be better handled using do-while loop which guarantees to execute its block at least once.

Given below is the sample code as per your requirement:

import java.util.Scanner;

public class Main {
    public static void main(String args[]) {
        Scanner scanner = new Scanner(System.in);

        int input = 0;
        int sum = 0;

        do {
            System.out.print("Enter number: ");
            input = scanner.nextInt();
            if (input > 100) {
                System.out.println("his number is already more than 100");
                break;
            }
            if (sum   input <= 100)
                sum  = input;

        } while (sum < 100);

        System.out.println("Sum of Numbers : "   sum);
    }
}

A sample run:

Enter number: 10
Enter number: 20
Enter number: 70
Sum of Numbers : 100

Another sample run:

Enter number: 101
his number is already more than 100
Sum of Numbers : 0
  • Related