如何合并以下if循环?

时间:2019-03-06 10:16:03

标签: java for-loop if-statement

我想将以下两个for循环和对应的if循环与break语句组合在一起。我怎样才能做到这一点。

public class Test {

    public static void main(String[] args) {

        for(int i=0;i<10;i++){
            if(i==2){
                System.out.println("i2: "+ i);
                break;
            }
            System.out.println("i2: "+ i);
        }

        for(int i=0;i<10;i++){
            if(i==4){
                System.out.println("i4: "+ i);
                break;
            }
            System.out.println("i4: "+ i);
        }
    }  
}

1 个答案:

答案 0 :(得分:0)

尝试

const nextBtn = document.querySelector('.nextBtn');
const prevBtn = document.querySelector('.prevBtn');
const container = document.querySelector('.images');

let colors = ['red', 'blue',];

let index = 0;

nextBtn.addEventListener('click', nextSlide);
prevBtn.addEventListener('click', prevSlide);

function nextSlide() {
  container.style.backgroundColor = colors[index];
  if(index <= colors.length){
    index++;
  }else{
    index = 0;
  }
}

function prevSlide() {
  container.style.backgroundColor = colors[index];
  if(index <= colors.length){
    index--;
  }else{
    index = 0;
  }
}




<div class="images">
    <button type="button" class="btn prevBtn">Prev Btn</button>
    <button type="button" class="btn nextBtn">Next Btn</button>
  </div>