#java #if-statement #conditional-statements #java.util.scanner #counter
#java #if-оператор #условные операторы #java.util.scanner #счетчик
Вопрос:
ПРИМЕЧАНИЕ: Сканер был импортирован в обоих наборах
в основном методе:
начало кода 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);
…конец кода set_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);
…конец кода set_2 ==> это переходит в бесконечный цикл.Почему?
что здесь не так с моей логикой? Насколько я понимаю, 1-е число хранится в numberbetweenAandB, и оно увеличивается с помощью счетчика до тех пор, пока цикл не закончится, и к этому времени переменная oddSum добавит все # s между a и b.
Ценю ваше время и усилия, направленные на это. Я все еще учусь.
Комментарии:
1. В вашем
while (numA <= numB)
цикле вы не обновляетеnumA
илиnumB
. Таким образом, цикл не может завершиться.2. Спасибо. ценю разъяснение. Очень очевидно, как я вижу это сейчас.
Ответ №1:
в вашем коде у вас есть:
while (numA <= numB){
// a bunch of code; and none of it changes numA or numB
}
очевидно, что тогда, если этот цикл while войдет хотя бы один раз, он войдет навсегда; numA и numB не меняются, поэтому, если это верно в начале, это будет верно навсегда.
Комментарии:
1. Спасибо. ценю разъяснение. Очень очевидно, как я вижу это сейчас.