我想创建一个for循环来询问并回答它的问题,但我想我想在for llop和idk中使用2个变量

问题描述 投票:0回答:1

公开课主课{

public static void main(String[] args) {

    String[] cars = new String[3];
    cars[0] = "bmw";
    cars[1] = "tesla";
    cars[2] = "lambo";

    String[] questions = new String[3];
    questions[0] = "What Is The First Car?";
    questions[1] = "What Is The Second Car?";
    questions[2] = "What Is The Third Car?";

    for (int i=0, x=1; i<questions.length, x<cars.length; i++, x++) {
        System.out.println(questions[i]);
        System.out.println(cars[x]);
    }

}

}

我不想要它简单,我想要它带有for循环,而不是那样:

       System.out.println("What is the first car?");
       System.out.println("bmw"); 

等等...如果有人知道请帮忙。

java arrays for-loop
1个回答
0
投票

按照 OldBoy 的说法,由于每个问题的索引对应于每个答案的索引,因此您只需要一个变量来表示该索引。

String[] cars = new String[3];
cars[0] = "bmw";
cars[1] = "tesla";
cars[2] = "lambo";

String[] questions = new String[3];
questions[0] = "What Is The First Car?";
questions[1] = "What Is The Second Car?";
questions[2] = "What Is The Third Car?";

for (int i = 0; i < questions.length; i++) {
  System.out.println(questions[i]);
  System.out.println(cars[i]);
}

希望这有帮助!

© www.soinside.com 2019 - 2024. All rights reserved.