【发布时间】:2020-12-27 08:35:52
【问题描述】:
注意:扫描仪在两组中都导入了
在main方法中:
代码 set_1 的开始...
Scanner input = new Scanner(System.in); //scanner for user input
System.out.print("Enter number, a: "); //prompt for user to enter number for variable, a
int numA = input.nextInt(); //variable for 1st number, a
int a = numA; //variable created to track 1st number entered - will be used to print later
System.out.print("Enter number, b: "); //prompt for user to enter number for variable, b
int numB = input.nextInt(); //variable for 2nd number, b
int oddSum = 0; //variable to hold calculation of total odd sum
//to loop between two numbers
while (numA <= numB){
//> 1 for odd #s to enter conditional
if ((numA % 2) > 0){
oddSum += numA; //variable, oddSum will store all added numbers between the 2 entered #s
}
numA++; //numA is counted +1
}
System.out.println("The sum of all odd numbers between " + a + " and " + numB + " is " + oddSum);
...代码集_1 结束 ==> 这 100% 有效
代码 set_2 的开始...
Scanner input = new Scanner(System.in); //scanner for user input
System.out.print("Enter number, a: "); //prompt for user to enter number for variable, a
int numA = input.nextInt(); //variable for 1st number, a
System.out.print("Enter number, b: "); //prompt for user to enter number for variable, b
int numB = input.nextInt(); //variable for 2nd number, b
int oddSum = 0; //variable to hold calculation of total odd sum
int numerBetweenAandB = numA; //variable created to track 1st # entered and count up
//to loop between two numbers
while (numA <= numB){
//> 1 for odd #s to enter conditional
if ((numA % 2) > 0){
oddSum += numberBetweenAandB; //variable, will store all added numbers between the 2 #s
}
numberBetweenAandB++; // counted +1
}
System.out.println("The sum of all odd numbers between " + numA + " and " + numB + " is " + oddSum);
...end of code set_2 ==> 这进入了一个无限循环。为什么?
我的逻辑有什么问题?据我了解 - 第一个数字存储在 numberbetweenAandB 中,并且使用 ++ 计数器上升,直到循环结束时,时间变量oddSum 已添加 a 和 b 之间的所有 #s。
感谢您为此付出的时间和精力。我还在学习。
【问题讨论】:
-
在您的
while (numA <= numB)循环中,您不会更新numA或numB。所以循环没有办法结束。 -
谢谢。感谢您的澄清。我现在看到的非常明显。
标签: java if-statement conditional-statements java.util.scanner counter