Java program infinite loop in sum of even integers - java

I am creating a program that prints the sum of the even numbers from a range of 0 to the number that the user entered. For example, if the user entered the number 20, the program would calculate the sum of all of the even numbers between 0 and 20.
When I tested the program out with the number 10, it worked. But I tried using a different number, 35, and it was just stuck in an infinite loop. I would appreciate any and all help. The code will be posted below:
(Edit) Thanks for the feedback everyone! After talking with a friend, we realized that the solution is actually pretty simple. We were just making it complicated. Still, thanks for all of the suggestions.
//**************************************************************
// Prints the sum of the even numbers within a range of 0
// and the integer that the user enters.
//
// #me
// #version_1.0_11.7.17
//**************************************************************
import java.util.Scanner;
public class EvenNumbersSum
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int user_num = 2; // variable that stores the user's number
int sum; // stores the sum of the needed values
System.out.print("Enter an integer greater than or equal to, 2: "); // prompt user for input
user_num = input.nextInt();
// checks to see if the value entered is valid or not.
while (user_num < 2)
{
System.out.println("Invalid entry. Must enter an integer greater than or equal to, 2.\n");
System.out.print("Enter an integer greater than or equal to, 2: ");
user_num = input.nextInt();
}
// starts adding the values
for (sum = 0; sum <= user_num;)
{
if (user_num % 2 == 0) // checks if the number is even
sum+=user_num; // add the number to sum
else
continue; // I thought that I might need this, but ended up changing nothing.
}
System.out.println(); // extra line for cleanliness
System.out.printf("The sum of the even numbers between 0 and %d is %d.", user_num, sum); // prints the result
}
}

Why are you writing loop for this, there are efficient way to do it.
Sum of numbers between 1-N = (N(N+1))/2
Sum of even numbers between 1-N = (N(N+2))/4
where N = user given input number till which you would like to add even numbers
NOTE: you can add validation on input number that it’s even by (n%2 == 0) and return error if it’s not

The variable you have used in condition (i.e. sum & user_num) no one changes in case of odd number and your code stuck in never-ending loop.
You should use counter variable ( e.g. i from 1 to user_num) and use that number in the condition. Example:
// starts adding the values
sum = 0;
for (int i = 0; i <= user_num; i++)
{
if (i % 2 == 0) // checks if the number is even
sum+=i; // add the number to sum
}

Your for loop should be like this.
int total_sum = 0;
for (int sum = 0; sum <= user_num; sum++)
{
if (sum % 2 == 0) // checks if the number is even
total_sum+=sum; // add the number to total sum
else
continue; // I thought that I might need this, but ended up changing nothing.
}
// note print total sum
System.out.println(totalsum);
your initial program just kept on checking entered number is even or odd.
And the entered number to sum.
So sum was always double of the entered number is even.
If entered number is odd it would go to infinite loop as entered_num(odd) % 2 == 0 always false and execute else statement.

Related

Why does my CalcOddIntegers method always return zero?

This method is supposed to take user input for the length of the array, and then the integers that are part of the array, and return the amount of odd numbers in the array. However, it always returns zero for the count of odd integers and I am unsure as to why. The scanner is declared outside of this method.
System.out.print("Enter length of sequence\n");
int length = console.nextInt();
int[] array = new int[length];
System.out.print("Enter the sequence: \n");
int count = 0;
int i = 0;
for (i = 0; i < length; i++) {
array[i] = console.nextInt();
}
for (i = 0; i < length -1; i++); {
if (array[i] % 2 != 0) {
count++;
}
}
System.out.printf("The count of odd integers in the sequence is %d\n", count);
}
Example of console:
2. Calculate the factorial of a given number
3. Calculate the amount of odd integers in a given sequence
4. Display the leftmost digit of a given number
5. Calculate the greatest common divisor of two given integers
6. Quit
3
Enter length of sequence
4
Enter the sequence:
1
2
3
4
The count of odd integers in the sequence is 0
I have tried experimenting with the for statements with different variables to see if something was conflicting but nothing has worked.
Remove the semi-colon (;) in the line
for (i = 0; i < length -1; i++);
the semi-colon terminates the loop hence an assumption that your line does nothing.
After the second for there is a semicolon that shouldn't be there. The syntax is technically correct however, there is nothing to execute so the block that checks for odd numbers is going to be executed only once. I suggest using a debugger that will help you troubleshoot issues easier.

Processing numbers program

Firstly, I'm taking AP Computer Science this year, and this question is related to an exercise we were assigned in class. I have written the code, and verified that it meets the requirements to my knowledge, so this is not a topic searching for homework answers.
What I'm looking for is to see if there's a much simpler way to do this, or if there's anything I could improve on in writing my code. Any tips would be greatly appreciated, specific questions asked below the code.
The exercise is as follows: Write a program called ProcessingNumbers that does:
Accepts a user input as a string of numbers
Prints the smallest and largest of all the numbers supplied by the user
Print the sum of all the even numbers the user typed, along with the largest even number typed.
Here is the code:
import java.util.*;
public class ProcessingNumbers {
public static void main(String[] args) {
// Initialize variables and objects
Scanner sc = new Scanner(System.in);
ArrayList<Integer> al = new ArrayList();
int sumOfEven = 0;
// Initial input
System.out.print("Please input 10 integers, separated by spaces.");
// Stores 10 values from the scanner in the ArrayList
for(int i = 0; i < 10; i++) {
al.add(sc.nextInt());
}
// Sorts in ascending order
Collections.sort(al);
// Smallest and largest values section
int smallest = al.get(0);
int largest = al.get(al.size() - 1);
System.out.println("Your smallest value is " + smallest + " and your largest value is " + largest);
// Sum of Even numbers
int arrayLength = al.size();
for (int i = 0; i < al.size(); i++) {
if (al.get(i) % 2 == 0) {
sumOfEven += al.get(i);
}
}
System.out.println("The sum of all even numbers is " + sumOfEven);
// Last section, greatest even number
if (al.get(arrayLength - 1) % 2 == 0) {
System.out.println("The greatest even number typed is " + al.get(arrayLength - 1));
} else {
System.out.println("The greatest even number typed is " + al.get(arrayLength - 2));
}
sc.close();
}
}
Here are specific questions I'd like answered, if possible:
Did I overthink this? Was there a much simpler, more streamlined way to solve the problem?
Was the use of an ArrayList mostly necessary? We haven't learned about them yet, I did get approval from my teacher to use them though.
How could I possibly code it so that there is no 10 integer limit?
This is my first time on Stackoverflow in quite some time, so let me know if anything's out of order.
Any advice is appreciated. Thanks!
Usage of the ArrayList wasn't necessary, however it does make it much simpler due to Collections.sort().
To remove the 10 integer limit you can ask the user how many numbers they want to enter:
int numbersToEnter = sc.nextInt();
for(int i = 0; i < numbersToEnter; i++) {
al.add(sc.nextInt());
}
Another note is that your last if-else to get the highest even integer doesn't work, you want to use a for loop, something like this:
for (int i = al.size() - 1; i >= 0; i--) {
if (al.get(i) % 2 == 0) {
System.out.println("The greatest even number typed is " + al.get(i));
break;
}
I wouldn't say so. Your code is pretty straightforward and simple. You could break it up into separate methods to make it cleaner and more organized, though that isn't necessary unless you have sections of code that have to be run repeatedly or if you have long sections of code cluttering up your main method. You also could have just used al.size() instead of creating arrayLength.
It wasn't entirely necessary, though it is convenient. Now, regarding your next question, you definitely do want to use an ArrayList rather than a regular array if you want it to have a variable size, since arrays are created with a fixed size which can't be changed.
Here's an example:
int number;
System.out.print("Please input some integers, separated by spaces, followed by -1.");
number = sc.nextInt();
while (number != -1) {
al.add(number);
number = sc.nextInt();
}
Here is a solution that:
Doesn't use Scanner (it's a heavyweight when all you need is a line of text)
Doesn't have a strict limit to the number of numbers
Doesn't need to ask how many numbers
Doesn't waste space/time on a List
Handles the case when no numbers are entered
Handles the case when no even numbers are entered
Fails with NumberFormatException if non-integer is entered
Moved actual logic to separate method, so it can be mass tested
public static void main(String[] args) throws Exception {
System.out.println("Enter numbers, separated by spaces:");
processNumbers(new BufferedReader(new InputStreamReader(System.in)).readLine());
}
public static void processNumbers(String numbers) {
int min = 0, max = 0, sumOfEven = 0, maxEven = 1, count = 0;
if (! numbers.trim().isEmpty())
for (String value : numbers.trim().split("\\s+")) {
int number = Integer.parseInt(value);
if (count++ == 0)
min = max = number;
else if (number < min)
min = number;
else if (number > max)
max = number;
if ((number & 1) == 0) {
sumOfEven += number;
if (maxEven == 1 || number > maxEven)
maxEven = number;
}
}
if (count == 0)
System.out.println("No numbers entered");
else {
System.out.println("Smallest number: " + min);
System.out.println("Largest number: " + max);
if (maxEven == 1)
System.out.println("No even numbers entered");
else {
System.out.println("Sum of even numbers: " + sumOfEven);
System.out.println("Largest even number: " + maxEven);
}
}
}
Tests
Enter numbers, separated by spaces:
1 2 3 4 5 6 7 8 9 9
Smallest number: 1
Largest number: 9
Sum of even numbers: 20
Largest even number: 8
Enter numbers, separated by spaces:
1 3 5 7 9
Smallest number: 1
Largest number: 9
No even numbers entered
Enter numbers, separated by spaces:
-9 -8 -7 -6 -5 -4
Smallest number: -9
Largest number: -4
Sum of even numbers: -18
Largest even number: -4
Enter numbers, separated by spaces:
No numbers entered

Java, can't find average of an array

I need to write a program that finds an average of all values in the array and then returns ones larger than the average.
import java.util.*;
public class AboveAverage {
public static void main(String args[]) throws Exception {
Scanner kbd = new Scanner(System.in);
int count=0, num;
int nums[] = new int[1000];
double sum = 0;
double average = 0;
System.out.println("Input +ve integers, to stop type 0");
num = kbd.nextInt();
while( num > 0 ) {
nums[count] = num;
count = count + 1;
num = kbd.nextInt();
}
int d = 0;
while ( d < 1000 ) {
sum += nums[d];
d++;
average = sum / nums[d];
}
for(int i=0; i < count ; i=i+1) {
System.out.print(nums[i] + " ");
}
System.out.println(average);
}
}
In my opinion problem is in this line
I tried the one below which gives an exception
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1000
at AboveAvarage.main(AboveAvarage.java:23)
average = sum / nums[d];
I also tried
average = sum / nums.length;
Which gave me the sum instead of the average.
Remember that array indices in Java go from zero? This means the allowed indices in your nums array are 0 through 999.
Now look at this loop:
int d = 0;
while ( d < 1000 ) {
sum += nums[d];
d++;
average = sum / nums[d];
}
First, it adds the current number to the sum. This is correct.
Then, it increments the number.
Then it uses the incremented number to access nums[d] to calculate the average.
Now, imagine that you are at the last round. d is 999.
First, it adds the current number to the sum.
Then it increments d. Now it is 1000.
Then it uses the incremented number to access nums[d]. But this means nums[1000]. And that's an illegal index.
So this explains why you have an ArrayIndexOutOfBoundsException. You should never use the index again after you incremented it, because the while only guaranteed that its previous value was less than 1000. If you change the value, you need to test again. This is why normally the increment step is the last in the loop.
As for your logic:
To calculate an average, you first need to know the sum. After you know the sum, you can divide by the number of items you are averaging. So you need to divide the sum by the number of items you read.
So:
You should not do a loop up to 1000. If you entered 0 after 5 numbers when you inputted the data, then there will be no values in the rest of the array (or rather, there will be zeros there).
You can calculate the sum, as another answer told you, in the first loop. No need to do that in the second loop.
You don't calculate the sum and the average in the same step. You first have to complete calculating the sum (finish the loop, be it the first or the second), and only then you can divide by the number of items (which you saved in count).
Then you have to go through another loop, that prints the numbers that are larger than the average. Your print loop prints all the numbers. You should check each number, see if it is greater than the average you calculated, and only if it is, print it.
Hint: there should really only be two loops: One that reads the numbers and calculates the count and the sum. Then you calculate the average, but that's not a repeating action, so it should not be in a loop. The second loop is for printing the numbers that are above average.
In the while loop that is gathering values, you are using count to track how many values are provided.
In the subsequent loop to calculate the average, you should only look at count items of the array:
int d = 0;
while(d<count) {
sum += nums[d];
}
average = sum/count;
Note you don't need to calculate average within the loop - do it once you've summed the values.
You don't need the other while loop, add up sum upon input. When done, just divide by count
while( num > 0 ) {
nums[count] = num;
count = count + 1;
sum += num;
num = kbd.nextInt();
}
average = sum / count;

java program outputting even/odd numbers

My task is to write a java program that first asks the user how many numbers will be inputted, then outputs how many odd and even numbers that were entered. It is restricted to ints 0-100. My question is: What am I missing in my code?
import java.util.Scanner;
public class Clancy_Lab_06_03 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int n;
System.out.println("How many numbers will be entered?");
n = input.nextInt();
while (n < 0 || n > 100) {
System.out.println("ERROR! Valid range 0-100. RE-Enter:");
n = input.nextInt();
n++;
}
int odd = 0;
int even = 0;
while (n >= 0 || n <= 100) {
n = input.nextInt();
if (n % 2 == 0) {
even++;
} else {
odd++;
}
}
System.out.println(even + "even" + odd + "odd");
}
}
Second while loop is infinite. Relplace it with something like this:
for (int i = 0; i < n; i++) {
int b = input.nextInt();
if (b % 2 == 0) {
even++;
} else {
odd++;
}
}
Also I don't understand why are you incrementing n in first loop. For example when you will first give -5, you will be asked to re-enter the number. Then you type -1, but it gets incremented and in fact program processes 0, altough user typed -1. In my opinion it is not how it suppose to work and you should just remove this n++.
As you asked in comment - the same using while loop:
while(n > 0) {
n--;
int b = input.nextInt();
if (b % 2 == 0) {
even++;
} else {
odd++;
}
}
Also it is good idea to close input when you no longer need it (for example at the end of main method)
input.close();
You had two issues - first you were incrementing n in the first loop, rather than waiting for the user to enter a valid number.
In the second loop, you weren't comparing the number of entries the user WANTED to make with the number they HAD made - you were over-writing the former with the new number.
This version should work, although I've not tested it as I don't have java on this machine.
Note that we now sit and wait for both inputs, and use different variable names for the "how many numbers will you enter" (n) and "what is the next number you wish to enter" (num) variables? Along with a new variable i to keep track of how many numbers the user has entered.
import java.util.Scanner;
public class Clancy_Lab_06_03
{
public static void main (String[] args)
{
Scanner input = new Scanner (System.in);
int n;
System.out.println ("How many numbers will be entered?");
n = input.nextInt();
//Wait for a valid input
while (n < 0 || n > 100)
{
System.out.println ("ERROR! Valid range 0-100. RE-Enter:");
n = input.nextInt();
}
//Setup variables for the loop
int odd = 0;
int even = 0;
int num;
//Keep counting up until we hit n (where n is the number of entries the user just said they want to make)
for(int i = 0; i < n; i++)
{
//Changed this, because you were over-writing n (remember, n is the number of entries the user wants to make)
//Get a new input
while (num < 0 || num > 100)
{
System.out.println ("ERROR! Valid range 0-100. RE-Enter:");
num = input.nextInt();
}
//Check whether the user's input is even or odd
if (num % 2 == 0)
{
even++;
}
else
{
odd++;
}
}
System.out.println(even + " even. " + odd + " odd.");
}
}
import java.util.Scanner;
public class Test2 {
public static void main(String[] args) {
System.out.println("Enter an Integer number:");
Scanner input = new Scanner(System.in);
int num = input.nextInt();
if ( num % 2 == 0 )
System.out.println("Entered number is even");
else
System.out.println("Entered number is odd");
}
}
My suggestion to you is to have a clear separation of your requirements. From your post, you indicate you need to prompt the user for two distinct data items:
How many numbers will be entered (count)
The values to be analyzed
It is a good practice, especially when you are learning, to use meaningful names for your variables. You are using 'n' for a variable name, then reusing it for different purposes during execution. For you, it is obvious it was difficult to figure out what was 'n' at a particular part of the program.
Scanner input = new Scanner (System.in);
int count;
System.out.println ("How many numbers will be entered?");
count = input.nextInt();
//Wait for a valid input
while (count < 1 || count > 100)
{
System.out.println ("ERROR! Valid range 1-100. RE-Enter:");
count = input.nextInt();
}
Additionally, a count of zero should not be valid. It does not make sense to run a program to evaluate zero values (don't bother a program that does nothing). I believe the lowest count should be one instead.
int odd = 0;
int even = 0;
int value;
do
{
System.out.print("Enter a number between 0 and 100: ");
value = input.nextInt();
while (value < 0 || value > 100)
{
System.out.println ("ERROR! Valid range 0-100. RE-Enter:");
value = input.nextInt();
}
if (value % 2 == 0)
{
even++;
}
else
{
odd++;
}
count--; // decrement count to escape loop
} while (count > 0);
System.out.println(even + " even. " + odd + " odd.");
This example uses a do/while loop because in this case, it is OK to enter the loop at least once. This is because you do not allow the user to enter an invalid number of iterations in the first part of the program. I use that count variable directly for loop control (by decrementing its value down to 0), rather than creating another variable for loop control (for instance , 'i').
Another thing, slightly off topic, is that your requirements were not clear. You only indicated that the value was bounded to (inclusive) values between 0 and 100. However, how many times you needed to repeat the evaluation was not really clear. Most people assume 100 was also the upper bound for your counter variable. Because the requirement is not clear, checking a value greater or equal to 1 for the count might be valid, although highly improbable (you don't really want to repeat a million times).
Lastly, you have to pay attention to AND and OR logic in your code. As it was indicated, your second while loop:
while (n >= 0 || n <= 100) {}
Is infinite. Because an OR evaluation only needs one part to evaluate to TRUE, any number entered will allow the loop to continue. Obviously, the intent was not allow values greater than 100. However, entering 150 allows the loop to continue because 150 >= 0. Likewise, -90 also allows the loop to continue because -90 <= 100. This is when pseudocode helps when you are learning. You wanted to express "a VALUE between lower_limit AND upper_limit." If you reverse the logic to evaluate values outside the limit, then you can say " value below lower_limit OR above upper_limit." These pseudocode expressions are very helpful determining which logical operator you need.
I also took the liberty to add a message to prompt the user for a value. Your program expects the user to enter two numbers (count and value) but only one prompt message is provided; unless they enter an out of range value.
extract even numbers from arrayList
ArrayList numberList = new ArrayList<>(Arrays.asList(1,2,3,4,5,6));
numberList.stream().filter(i -> i % 2 == 0).forEach(System.out::println);

I need to make two to the input value inclusive

/*
* Application the reads an integer and prints sum of all even integers between two and input value
*/
import java.util.Scanner;
public class evenNumbers{
public static void main(String [] args){
int number;
Scanner scan = new Scanner(System.in);
System.out.println("Enter an Integer greater than 1:");
number = scan.nextInt();
printNumber(number);
}// end main
/*declares an int variable called number and displays it on the screen*/
public static void printNumber(int number){
if (number < 2){
System.out.println("Input value must not be less than 2");
}
int sum = 2;
if(number % 2==0){
sum+= number;
}
System.out.println("Sum of even numbers between 2 and " + number + " inclusive is: " + sum);
}//end printnumber
}
I need to calculate the sum of 2 to the input number inclusive however, it only takes the last number and add two to it. COuld someone help me fix this.
You need a loop. Your comment hints at the right direction, but you should look at the Java tutorials to see how to correctly write a 'for' loop. There are three parts: the initial declaration, the terminating condition and the loop step. Remember that the ++ operator only adds one to the variable. You can add other values using +=. If you use += to add a different value (like 2) to the loop variable, you can skip the 'if' test for even numbers. You can test for boundaries inclusively using the <= and >= comparison operators (for primitives). So you want something like this (in pseudocode, not Java):
input the test value
Optional: reject invalid test value and **exit with message if it is not valid!**
initialize the sum variable to zero
for ( intialize loop variable to 2; test that loop var <= test value; add 2 to loop var )
{
add 'number' to the sum variable
}
display the sum
int sum = 0;
for (int current = 2; current <= number; current += 2)
sum += current;

Categories