[英]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:我有以下任务:
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.如果数字小于 100,则要求用户输入另一个数字并将它们相加。
Keep asking the user to enter numbers until the sum of all entered numbers is at least 100.不断要求用户输入数字,直到所有输入数字的总和至少为 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.如果用户输入的第一个数字大于或等于100,则打印“这个数字已经大于100”,并且不要求用户输入任何其他数字。
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.即使我使用
break
,它也会在 100 号之后中断。
This problem can be better handled using do-while loop which guarantees to execute its block at least once.使用 do-while 循环可以更好地处理这个问题,该循环保证至少执行一次其块。
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.