Java作业循环选择咨询:求两整数间所有数的和该用while还是for?
Hey there! Let's tackle this problem together since you're just getting the hang of loops. First, let's make sure we're on the same page about the requirement:
输入两个整数,求它们之间所有数的和;若两数之间无间隔,输出0
先用你熟悉的while循环实现
First, let's outline the steps we need to take:
- 读取两个输入的整数
- 确定哪个数更大,哪个更小(这样我们不用管输入顺序,比如输入5和3也能正确计算)
- 用while循环遍历两个数之间的所有数,累加求和
- 如果两个数相邻或者相等,直接输出0
Here's the code with detailed comments to help you follow along:
import java.util.Scanner; public class SumBetweenNumbers { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); // 获取两个输入整数 System.out.print("请输入第一个整数:"); int num1 = scanner.nextInt(); System.out.print("请输入第二个整数:"); int num2 = scanner.nextInt(); // 确定最小值和最大值,避免输入顺序影响结果 int min = Math.min(num1, num2); int max = Math.max(num1, num2); int sum = 0; // 从min的下一个数开始,直到max的前一个数 int current = min + 1; // while循环条件:current必须小于max,否则说明没有中间数 while (current < max) { sum += current; // 把当前数加到总和里 current++; // 移动到下一个数 } // 输出结果,如果min和max相差<=1,sum就是0,正好符合要求 System.out.println("两数之间所有数的和是:" + sum); scanner.close(); } }
聊聊for循环:它的运行机制,以及是否适合这个场景
You mentioned you're not sure how for loops work—let's break that down simply. A for loop is just a more compact way to write loops where you have an initialization, a condition, and an iteration step all in one line.
The structure of a for loop looks like this:
for (初始化语句; 循环条件; 迭代语句) { // 循环体:条件满足时执行的代码 }
- 初始化语句:只在循环开始前执行一次(比如设置起始值)
- 循环条件:每次循环开始前判断,如果为true就执行循环体,否则退出循环
- 迭代语句:每次循环体执行完后执行(比如让变量自增)
For this problem, a for loop is actually just as suitable as a while loop—maybe even a bit cleaner, since we can put the current variable's initialization and increment right in the loop definition. Here's what the for loop version would look like:
// 前面的输入和min/max部分和while版本一样 int sum = 0; // 初始化current为min+1,条件是current < max,每次循环后current自增1 for (int current = min + 1; current < max; current++) { sum += current; } System.out.println("两数之间所有数的和是:" + sum);
该选while还是for?
Since you're already comfortable with while loops, using that is totally fine—there's no "better" choice here, just different styles. The for loop is just a shorthand for when you have a clear starting point, condition, and step to iterate. As you get more practice, you'll start to feel which one fits better for different scenarios, but for this problem, both work perfectly.
内容的提问来源于stack exchange,提问作者jp89lawson

