Checking if a number entered is odd
`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);开发者_如何学JAVA
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!");
}
}
}
Use modular arithmetic:
if (number % 2 == 0) {
// even
} else {
// odd
}
Update:
You can test this code here:
- https://repl.it/Hkc6/1
Beware that checking for evenness with number % 2 == 1
will fail.
To check if a number is odd, you can use (number & 1) != 0
.
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;
}
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.
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
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.
精彩评论