Pregunta

Okay so I need to make a number pattern with day numbers for example: 1 - monday, 2 - tuesday, 3 - wednesday until 7 - sunday. If I put an input "n" I would get the following:

n=4
1 2 3 4

n=7
1 2 3 4 5 6 7

n=12
1 2 3 4 5 6 7 1 2 3 4 5

I've succeeded making this program if n<=14 but if n>14 I get:
n=17
1 2 3 4 5 6 7 1 2 3 4 5 6 7 8 9 10
when it should be:
n=17
1 2 3 4 5 6 7 1 2 3 4 5 6 7 1 2 3

this is my code

for (x=1;x<=n;x++){
    System.out.print(x+" ");
    if (x==7){
        for (x=1;x<=(n-7);x++)
        System.out.print(x+" ");
        break;
    }
}

thanks in advance

¿Fue útil?

Solución

Try this instead:

for (int i = 0; i < n; i++)
    System.out.print(i % 7 + 1 + " ");

Whenever you want to have that "repeating" behavior, where a sequence of numbers goes up to a certain value and then restarts, use the % operator and a bit of modular arithmetic to achieve the desired effect. For n = 17 the above will print:

1 2 3 4 5 6 7 1 2 3 4 5 6 7 1 2 3
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top