-4

Как сделать цикл 1,2,3,1,2,3,1,2,3,...

2
  • 3
    while (true) {i=(i%3)+1;...}
    – Akina
    3 апр 2018 в 19:46
  • Переформулируйте вопрос понятнее.
    – iramm
    4 апр 2018 в 22:35

5 ответов 5

2

Вам следует описывать вопрос более развернуто, но постараюсь угадать, кажется вам нужно это:

    int i=1;
    while(true){
        System.out.println(""+i++);
        if(i>3)i=1;
    }
2

Еще вариант :-)

public class Cycle {
    public static void main(String[] args) {
        int i;
        while (true) {
            for (i = 1; i <= 3; i++) {
                System.out.print(i + ",");
            }
        }
    }
}
2

Еще вариант:

Stream.generate(() -> Stream.of(1,2,3))
        .flatMap(Function.identity())
        .limit(9) //если убрать limit, то будет бесконечный стрим
        .forEach(System.out::println);
1
  • Классное решение. я пытался что то похожее через стримы сделать, но ваш вариант намного элегантнее
    – Artem
    9 апр 2018 в 7:44
1

Можно так:

 IntStream
          .generate(new IntSupplier() {
                private int index = 0;

                @Override
                public int getAsInt() {
                    return (index++) % 3 + 1;
                }})
          .forEach(System.out::println);
0

+ 1 вариант:

    public class Cicle {
        public static void main(String[] args) {
            int[] a = {1, 2, 3};
            while (true) {
                for (Integer integer : a) {
                    System.out.print(integer + ",");
                }
            }
        }
    }

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.