问题描述
注意:两组扫描仪均已导入
在主要方法中:
代码集_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);
...代码set_1的结尾==>可以100%工作
代码集_2的开头...
Scanner input = new Scanner(system.in); //scanner for user input
System.out.print("Enter number,a
System.out.print("Enter 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);
...代码set_2的结尾==>这会陷入无限循环。为什么?
在这里我的逻辑有什么问题?据我了解-第一个数字存储在numberbetweenAandB中,并且使用++计数器进行递增,直到循环结束为止,此时,时间变量sumSum已将a和b之间的所有#都加了。
感谢您为此花费的时间和精力。我还在学习。
解决方法
在您的代码中,您具有:
while (numA <= numB){
// a bunch of code; and none of it changes numA or numB
}
显然,如果