Why do even numbers not have the same output as odd numbers?

Asked

Viewed 61 times

1

I made a program that asks the user for a number that will serve maximum value. And then the program shows which even and odd numbers from 0 to that number. I used printf to have an output like:

Os números pares são os seguintes:
2   4   6   8  10

But yet I have the following output:

Os números pares são os seguintes:

2

4

6

8

10

I don’t understand why since in odd numbers output is the intended output but in pairs it is not. There is the code I used:

{
    String repetir = " " ;
    do
    {
        System.out.println("Indique um valor máximo");
        int max = scanner.nextInt();
        int par= 0;
        int impar = 0;

        System . out . println("Os números pares são os seguintes:");
        while(par<= max)
        {

            if (par%2 == 0)
            {
                System . out . printf ("%3d",par); 
                System.out.println("   ");
            }
            par++;
        }
        System . out . println("Os números impares são os seguintes:");
        while (impar <= max)
        {
            if (impar %2 != 0)
            {
                System . out .printf ("%3d",impar); 
            }
            impar++;
        }
        System.out.println("   ");
        System.out.println("Deseja repetir a operação?(s/n)");
        repetir = scanner.next();
    }while (repetir.equals("s"));
}
  • What’s the difference? What do you see wrong?

  • The exercise that asks me to do this speaks specifically in the output however I think I used the same type of code for even numbers as odd however the output is another

  • The answers solved your problem?

2 answers

5


Just remove the line

System.out.println("   ");

Why do you print an empty row after each even number

if (par%2 == 0)
{
    System . out . printf ("%3d",par); 
    System.out.println("   "); // <--------
}
par++;

And the odd ones don’t

if (impar %2 != 0)
{
    System . out .printf ("%3d",impar); 
}
impar++;

4

Remove that line:

System.out.println("   ");

Browser other questions tagged

You are not signed in. Login or sign up in order to post.