Question: My java code is creating an infinite loop and I can't figure out how to make it sum the odd numbers without creating the infinite
My java code is creating an infinite loop and I can't figure out how to make it sum the odd numbers without creating the infinite loop. Any help would be greatly appreciated. The instructions for this assignment are below:
Write an application that reads two integers from the user and prints the sum of the odd numbers between these two numbers, inclusive. For example, if the user entered 5 and 10, the answer would be 21 (5 + 7 + 9). You cannot assume the first number is smaller than the second number.
The code below is what I have thus far for this problem.
import java.util.Scanner;
public class Integers { int sum= 0; public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.print("Please enter an integer: "); int number1 = input.nextInt(); input = new Scanner(System.in); System.out.print("Please enter another value: "); int number2 = input.nextInt(); int i = number1; if (number1 % 2 != 0) { ++number1; } while (i <= number2) { sum +=i;
System.out.println(sum); while (i <= number2) { System.out.println(i); } i++; } } }
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
