Reputation: 43
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:
Write a program that asks the user to enter a number.
If the number is less than 100, then ask user to enter another number and sum both of them.
Keep asking the user to enter numbers until the sum of all entered numbers is at least 100.
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
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