Julian Petty :
My instructions are "Write a program that prompts the user for a number, then counts up (a ‘for’ loop) from one to that number and prints whether that loop number is even or odd (which will require an ‘if-else’ structure inside the loop)." So it needs to list: 1 is odd 2 is even 3 is odd...
public class AssmtEvenOrOddJulianP {
public static void main(String[] args) {
//variable
int num = 0;
//input
System.out.print("\nEnter a number less than 100: ");
num = Expo.enterInt();
//output
for (int i = 1; i <= num; i++)
if ((num % 2) == 0)
System.out.print("\n" + i + " Is Even");
else if ((num % 2) >= 0)
System.out.print("\n" + i + " Is Odd");
Right now if I input 3 it will print: 1 is odd 2 is odd 3 is odd
Behrang Saeedzadeh :
Always wrap
The
The
Minor mistake:
You should calculate the remainder of i
by 2, not num
by 2.
Always wrap for
and if
/else
blocks in curly braces:
for (int i = 1; i <= num; i++) {
if ((i % 2) == 0) {
System.out.print("\n" + i + " Is Even");
} else if ((num % 2) >= 0) {
System.out.print("\n" + i + " Is Odd");
}
}
Avoid using redundant parantheses:
for (int i = 1; i <= num; i++) {
if (i % 2 == 0) {
System.out.print("\n" + i + " Is Even");
} else if (num % 2 >= 0) {
System.out.print("\n" + i + " Is Odd");
}
}
The else if
condition has a minor bug that is "unreachable" right now, but could cause pain in the future
num % 2 >= 0
should be i % 2 < 0 || i % 2 > 0
The else if
condition can be simplified to else
:
for (int i = 1; i <= num; i++) {
if (i % 2 == 0) {
System.out.print("\n" + i + " Is Even");
} else {
System.out.print("\n" + i + " Is Odd");
}
}
Final result:
With some other minor improvements:
public class EvenOdd {
public static void main(String[] args) {
// input
System.out.print("\nEnter a number less than 100: ");
// variable
int num = Expo.enterInt();
System.out.println();
// output
for (int i = 1; i <= num; i++) {
if (i % 2 == 0) {
System.out.println(i + " Is Even");
} else {
System.out.println(i + " Is Odd");
}
}
}
}