Checking if a number entered is odd
Asked Answered
R

5

12

`I'm not sure what code to insert or even where, but I would like to check the number I enter is an odd number.

import java.io.*;
import javax.swing.JOptionPane;

public class Diamond {
    public static void main(String [] args) throws IOException {

        BufferedReader stdin = new BufferedReader (new InputStreamReader (System.in));
        String input; 
        int num;
        System.out.println("input number: ");
        input = stdin.readLine ();
        num = Integer.parseInt(input);

        if (num % 2 ==1){
            int d = num;
            int e = 0;
            for (int a = 0; a <= num; a++) {
                for (int c = d; c>= 1; c-- )
                    System.out.print(" ");
                d-=1;
                for (int b = 1; b <= a; b++)
                    System.out.print ("* ");
                System.out.println();
            }

            num-=1;
            for (int a = 0; a<=num; a++) {
                for (int b = num; b > a; b--)
                    System.out.print (" *"); 
                System.out.println(); 
                for (int c = 0; c <= e; c++)
                    System.out.print(" ");
                 e+=1;
            }
        } else {
            System.out.println("Please enter an odd number!");
        }
    }
}
Rugg answered 11/3, 2011 at 18:37 Comment(5)
Mike, you don't put code between [code] and [/code] here. I just selected it and clicked on the code icon; another way when using code blocks is to indent it four spaces.Murielmurielle
I'm sorry, but I can't get the code to show up correctly in the post.Rugg
I added the if-else statement, but don't think it's correct.Rugg
Pull input = stdin.readLine (); num = Integer.parseInt(input); out of the if block, num must be initialised before being checked.Terrorist
Why is that a community wiki page?Doddered
E
51

Use modular arithmetic:

if (number % 2 == 0) {
  // even
} else {
  // odd
}

Update:

You can test this code here:

Beware that checking for evenness with number % 2 == 1 will fail.

To check if a number is odd, you can use (number & 1) != 0.

Emmetropia answered 11/3, 2011 at 18:40 Comment(3)
Just as a quick reply, in Python you could do: int(z / 2) == float(z) / 2 but most will use the obvious %.Emmetropia
number % 2 means the remainder of dividing number by 2. All even numbers will not produce a remainder, and all odd numbers will.Delacroix
Incorrect results on negative numbers… down vote. :(Countersignature
A
11

num % 2 == 1 return incorrect results on negative Odd number, the remainder of division with 2 will not be 1. This can be fixed as follows:

public boolean isOddNumber(int num) {
    return (num & 1) != 0;
}
Advised answered 11/3, 2011 at 18:37 Comment(1)
Java Findbugs prefers this method tooArmageddon
F
6

You can NOT have readLine inside of that if. First you need to get the value and next you can use your if.

It goes like this:

BufferedReader stdin = new BufferedReader (new InputStreamReader (System.in));

String input; 
int num;

System.out.println("input number: ");

  input = stdin.readLine();
  num = Integer.parseInt(input);

if (num % 2 == 1) {
// odd
} else {
  System.out.println("Please enter an odd number!");
}

Finally - do NOT use values named "a", "e" or "d" - it's very confusing. Just name vars with names that let reader know/guess their role in your code. I have no idea what is the meaning of your "a" or b, c, d etc. For example, your num should be named enteredValue to clarify your code.

Foumart answered 11/3, 2011 at 18:37 Comment(5)
I changed it, but something is not where it should be. When I enter an even number it does nothing. If I enter an odd number it works fine.Rugg
Id like to help u, but ur code is awful to read. U need to rename ur variables... add some private functions in place of multiple code line inside of if-else -> if - function1() (named correctly!) else - function2() ... introcs.cs.princeton.edu/11style read it plz, or google sth else bout clear code and remeber - code needs to be easy to read!Foumart
Please refrain from using text-speak in your answers and your comments. This is a site for professional and enthusiast programmers, and as such expects at least some level of professionalism in questions and answers.Bowyer
@Rob Hruska so be profesional and help Mike in place of learning me to use "you" in place of "u". I just want to help, not to act like someone elseFoumart
Using full words (e.g. "you" instead of "u", "your" instead of "ur") makes your answers easier to read and comprehend. Since there's no limit on the size of the content, there's no reason not to take the time to spell things out and make your answers legible. It will also help others to take your answer more seriously, so it serves your interests as someone trying to help.Bowyer
T
2

Chaker's answer about negative integer is confirmed. In my JavaSE-1.8

System.out.println( "result =" + ( -3 % 2 == 1) );


it shows result =false instead true

Tardigrade answered 11/3, 2011 at 18:37 Comment(0)
F
1

Bitwise operation (bit manipulation) way in Java

if ((num & 1) != 0) //odd
{
     //do something here
} else { //even
    //do something here
}

works by looking at say, 100 (number 4) vs 001, doing the AND operation on each bits and returning either 0 and 1. If the end bit is a 0, like 4, it's always going to be even. If the end bit is 1, it is going to be odd.

Fractional answered 11/3, 2011 at 18:37 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.