我想总结两个数字之间的值范围。我提示用户输入2个数字,如果第一个数字更大,那么我想在循环之前将它与第二个数字交换。我怎么能这样做?
import java.util.Scanner;
public class Example {
public static void main (String []args) {
Scanner kb = new Scanner(System.in);
int n1 = 0, n2 = 0, count = 0;
System.out.print("Enter two limits: ");
n1 = kb.nextInt();
n2 = kb.nextInt();
while ( n1 <= n2 ) {
count = count + n2;
n2--;
}
System.out.println("The sum from "+ n1 +" to "+ n2 +" is : " + count);
}
}
我想要的输出告诉我(如果我输入6和10)
the sum from 6 to 10 is 40
但是我的程序输出是
the sum from 6 to 5 is 40
我做错了什么?
答案 0 :(得分:3)
可以使用Math.max(int, int)
和Math.min(int, int)
(以及IntStream
,假设您使用的是Java 8+)。像,
Scanner kb = new Scanner(System.in);
System.out.print("Enter two limits: ");
int n1 = kb.nextInt();
int n2 = kb.nextInt();
int start = Math.min(n1, n2), stop = Math.max(n1, n2);
System.out.println("The sum from " + n1 + " to " + n2 + " is : "
+ IntStream.rangeClosed(start, stop).sum());
如果由于某种原因你不能使用Math
,或者是一个非常方便的小技巧,你可以做一些你自己的数学;像
int start = n1;
if (n2 < n1) {
start = n2;
}
int stop = n2 + n1 - start;
或强>
int start = (n1 < n2) ? n1 : n2, stop = n2 + n1 - start;
答案 1 :(得分:0)
Scanner in = new Scanner(System.in);
int n1;
int n2;
int count = 0;
System.out.print("Enter two limits: ");
n1 = in.nextInt();
n2 = in.nextInt();
if (n1 > n2) {
n1 += n2;
n2 = n1 - n2;
n1 -= n2;
}
int current = n1;
while (current <= n2) {
count += current;
current++;
}
System.out.println("The sum from " + n1 + " to " + n2 + " is : " + count);