0

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");
    }
}
6
  • What behavior are you seeing? Also, it might help to break your program into smaller chunks (eg one for taking input; one for generating output) that you can test independently. Commented Oct 14, 2014 at 14:20
  • What is/isn't happening that you're expecting? Your code looks sensible at first glance. Commented Oct 14, 2014 at 14:21
  • From your description, it seems like you should be taking in only the specified amount of numbers, but your while loop keeps going as long as the input is valid... Commented Oct 14, 2014 at 14:22
  • while (n >= 0 || n <= 100) : always true, infinite loop Commented Oct 14, 2014 at 14:23
  • you are using the variable n as counter (how many numbers will be entered) and for the entered number. use 2 different variables. besides you have to decrease the variable for the counter in the correct while-loop. Commented Oct 14, 2014 at 14:24

5 Answers 5

2

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();
Sign up to request clarification or add additional context in comments.

1 Comment

Just curious, what would be the while loop equivalent of this for loop?
0

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.");
    }
}

Comments

0
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");
    }
}

Comments

0

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:

  1. How many numbers will be entered (count)
  2. 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.

Comments

-1
  • 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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.