gpt4 book ai didi

java - 如何在Java中创建一个循环数组,只打印数组的次数?

转载 作者:行者123 更新时间:2023-12-02 03:16:09 24 4
gpt4 key购买 nike

当尝试制作测验制作代码时:我想询问问题的数量,然后创建那么多的问题,并能够返回每个问题。我很困惑为什么输出不是逐行输出和输入。我已经导入了 java.io.* 和 java.util.*

public class quiz {
public static void main(String []args){

Scanner kbReader = new Scanner(System.in);
System.out.println("~@{@{@{{{{{{{{{{{{{{{{{{ Quizmaker }}}}}}}}}}}}}}}}}}@}@}@~");
System.out.println("How many questions are in this quiz?");
int numberoQuestions = kbReader.nextInt();
//lets make this input 4
String question [] = new String [numberoQuestions]; //the questions the user has made
int createdQs = 0; //how many questions the user has made

do {
createdQs ++;
System.out.println("What is question " + createdQs);
question [createdQs]= kbReader.nextLine();
}
while(createdQs <= numberoQuestions);
/*
supposed to print
How many questions are in this quiz?
(4)
What is question 1?
(input)
What is question 2?
(input)
What is question 3?
(input)
What is question 4?
(input)

it instead prints
How many questions are in this quiz?
4
What is question 1
What is question 2
age?
What is question 3
height?
What is question 4
school?
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4
at finalProject.quiz.main(quiz.java:18)

*/
System.out.println(question[3] );//prints question 4 but I want it to print question 3
}
}

最佳答案

使用scanner.readLine()调用 nextInt() 后消耗缓冲区中剩余的换行符,移动createdQs++;do-while结束循环,并将循环条件更改为createdQs < numberoQuestions (因为数组从 0 开始并转到 length-1 )。

关于java - 如何在Java中创建一个循环数组,只打印数组的次数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40267535/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com