brmk
brmk

Reputation: 43

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

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 += input;
}

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

I have the following task:

If the first number entered by the user is more than or equal to 100, print message “This number is already more than 100” and do not ask the user to enter any other numbers.

I can print the sum of numbers entered by user but I just can't stop it. Even if I use break, it breaks after the 100 number.

Upvotes: 1

Views: 2584

Answers (1)

Arvind Kumar Avinash
Arvind Kumar Avinash

Reputation: 79435

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

Upvotes: 1

Related Questions