Pizzaman
Pizzaman

Reputation: 425

Find lowest odd number in a loop

I know this code is wrong. I'm a beginner so bear with me.

I need to find the lowest odd number but it keeps coming up as zero no matter what numbers are entered. I need to initialize 'lowest' but how/where do I initialize it?

lowest = 0 is causing a problem but I'm not sure where to initialize lowest

class Odd

{
    public static void main(String[] args)
    {
        int number; //the number entered by the user
        int input; //the amount of numbers to be entered by the user
        int index;
        int lowest = 0; //lowest odd number

        System.out.println("How many numbers? ");
        input = EasyIn.getInt();

    for (index = 1; index <= input ; index ++) 
        {
            System.out.println("Enter number " + index + ":" );
            number = EasyIn.getInt();

            if ((number % 2 == 1) && (number < lowest)) 
            {
                lowest = number;    
            }

        }

    System.out.println("The lowest odd number entered was " + lowest);

    }
}

Upvotes: 1

Views: 230

Answers (3)

Peter Lawrey
Peter Lawrey

Reputation: 533530

You are starting at 0 so you will not get a value larger. If you start like this

int lowest = Integer.MAX_VALUE;

Also (n % 2) will only be 1 for positive numbers. If you want to test for odd negative numbers you want (n & 1) != 0


Note: Integer.MAX_VALUE is an odd number so even if this is the only value it will be the maximum. However, if you want to be able to tell the difference between some one entering this value and no odd values you can use this instead.

long lowest = Long.MAX_VALUE;

This will allow you to tell the difference between Integer.MAX_VALUE being entered and no value as Long.MAX_VALUE is much higher.

Upvotes: 4

rich
rich

Reputation: 19414

You initialise lowest as 0 and then look for numbers lower than it (and odd).

I'd initialise it as EasyIn.getInt() so it's the first number in your list to check through.

Upvotes: 1

Denys S&#233;guret
Denys S&#233;guret

Reputation: 382160

If you're sure your input isn't empty, a solution is to initialize lowest to a big enough value :

int lowest = Integer.MAX_VALUE;

This ways all values will be smaller, so lowest will be one of the values of your input.

Upvotes: 6

Related Questions