Not Looping? (do - while) bad execution!
this program only asks me the first input then the whole program stops
Code :
public static void main(String[] args) {
int count = 0;
System.out.print("Enter The Max Value: ");
int max = sc.nextInt();
System.out.print("Which Value Do You Want To Display Even Or Odd?");
String answer = sc.nextLine();
do {
count++;
if (answer.equalsIgnoreCase("even")) {
if (count % 2 == 0) {
System.out.println(count);
}
}
}
while (count != max);
}
}
Re: Not Looping? (do - while) bad execution!
There's no case to handle the odd numbers. Also, because of the funny implementation of nextInt(), it's not consuming the next line character when you input the max value.
Also, there is a much better method to print out odd/even numbers: use an if statement for even/odd, then iterate through all even/odd numbers up to max.
Code :
System.out.print("Enter The Max Value: ");
int max = sc.nextInt();
System.out.print("Which Value Do You Want To Display Even Or Odd?");
sc.nextLine(); // consume \n from above
String answer = sc.nextLine();
if ("even".equalsIgnoreCase(sc))
{
for (int i = 0; i < max; i+=2)
{
System.out.println(i);
}
}
else if ("odd".equalsIgnoreCase(sc))
{
for (int i = 1; i < max; i+= 2)
{
System.out.println(i);
}
}
else
{
System.out.println("You didn't enter even or odd. quiting.");
}