Java程序没有对象添加到ArrayList的 [英] Java program doesn't add objects to ArrayList
问题描述
我尝试不同的对象添加到的ArrayList
键,它不工作。我不知道这是否是因为我错误地将对象或如果有别的东西是错误的。
下面是我的code。
进口的java.util。*;
进口java.io. *;公共类QuizBowl实现测验{
私人Player播放器; //播放器对象
私人字符串的文件; //文件的名称。
私人诠释qNum; //问题球员的数量要回答
私人诠释qNumFile; //在文件中的问题数
私人的ArrayList<问题> questionsArr; //保存对象的问题
私人布尔questionsAsked []; //问题阵列已经问 //构造
公共QuizBowl(字符串FNAME,LNAME字符串,字符串文件)抛出FileNotFoundException异常{
玩家=新播放器(FNAME,LNAME);
扫描仪gameFile =新的扫描仪(新File(文件));
qNum = numOfQuestionsToPlay();
qNumFile = maxNumQFile(gameFile);
questionsArr =新的ArrayList<问题>();
ReadFile的();
的System.out.println(questionsArr);
questionsAsked =新的布尔[qNumFile]
的System.out.println(Arrays.toString(questionsAsked));
} //要求用户有多少问题要问
公众诠释numOfQuestionsToPlay(){
扫描仪控制台=新的扫描仪(System.in); //检查有效用户输入
布尔检查= FALSE;
做{
尝试{
System.out.print(有多少问题,你想(出3)?);
INT答案= console.nextInt();
如果(回答→3){
的System.out.println(对不起,这是太多了。);
检查= FALSE;
}
其他{
检查= TRUE;
}
}
赶上(InputMismatchException时五){
的System.out.println(无效的输入请再试一次。);
console.nextLine();
检查= FALSE;
}
}
而(检查==假);
返回qNum;
} //计算出有多少问题是在文件中
公众诠释maxNumQFile(扫描仪gameFile){
INT NUM = gameFile.nextInt();
返回NUM;
} //循环用于读取质询
公共无效ReadFile的(){
的for(int i = 0; I< qNum;我++){
readQuestion();
}
} // READS问题问题后,并增加了质询物体的ArrayList中
公共无效readQuestion(){
扫描仪控制台=新的扫描仪(System.in);
console.nextLine();
的String []线;
串问题,questionType;
INT点; 行= console.nextLine()分裂()。 questionType =行[0];
点=的Integer.parseInt(行[1]);
问题= console.nextLine(); 如果(questionType.equals(MC)){//检查,如果问题类型是MC
questionsArr.add(readMC(questionType,问题点,控制台)); //添加MC问题阵
}
否则,如果(questionType.equals(SA)){//检查的问题类型是SA
questionsArr.add(readSA(questionType,问题点,控制台)); //添加SA回答的数组
}
其他{//检查,如果问题类型是TF
questionsArr.add(readTF(questionType,问题点,控制台)); //添加TF问题阵
}
} //读取一个TF问题
公共静态QuestionTF readTF(字符串questionType,字符串问题,INT点,扫描仪控制台){//返回新QuestionTF对象
串ANS = console.nextLine();
返回新QuestionTF(问题,questionType,点,ANS);
} //读取一个SA问题
公共静态QuestionSA readSA(字符串questionType,字符串问题,INT点,扫描仪控制台){
串ANS = console.nextLine();
返回新QuestionSA(问题,questionType,点,ANS); //返回新QuestionSA对象
} //读取一个MC问题
公共静态QuestionMC readMC(字符串questionType,字符串问题,INT点,扫描仪控制台){
INT numChoices;
的String []选择;
答串;
numChoices =的Integer.parseInt(console.nextLine());
选择=新的String [numChoices]
ANS = console.nextLine(); 的for(int i = 0; I< numChoices;我++){
选择[I] = console.nextLine();
} 返回新QuestionMC(问题,questionType,点,选择,ANS); //返回新QuestionMC对象
} // STARTS测验
公共无效测验(){
INT qCount = 0;
INT ranQ;
扫描仪userInput =新的扫描仪(System.in);
串userAns; 随机R =新的随机(); // RUNS测验
而(qCount< qNum){
ranQ = r.nextInt(qNumFile); //检查,如果问题已经被问
如果(!checkDup(ranQ,questionsAsked)){
questionsAsked [ranQ] = TRUE;
问题question = questionsArr.get(ranQ); // GETS随机抽题从Array
question.printQuestion(); //输出问题点
userAns = userInput.next(); //从用户获取答案
; //检查用户的答案
如果(userAns.equals(跳过)){
的System.out.println(您选择跳过这个问题。);
}
其他{
checkAnswer(userAns,问题球员);
} qCount ++;
的System.out.println();
}
}
} //检查,如果问题已经被问
公共布尔checkDup(INT ranQ,布尔questionsAsked []){
返回questionsAsked [ranQ]
}
// CHECKS ANSWER,并增加了点
公共无效checkAnswer(字符串userAnswer,问的问题,Player播放器){
如果(question.checkAnswer(userAnswer)){
的System.out.println(正确的你+ question.getPoints());
player.setScore(question.getPoints());
}
其他{
的System.out.println(不正确的,得到的答复是+ question.getAnswer()+。+
你输+ question.getPoints()+。);
player.setScore(question.getPoints()* -1);
}
} //执行程序
公共静态无效的主要(字串[] args)抛出FileNotFoundException异常{
扫描仪控制台=新的扫描仪(System.in);
System.out.print(请输入您的名字:);
串第一= console.next();
System.out.print(请输入您的姓氏:);
字符串最后= console.next();
System.out.print(请输入游戏文件名称:);
字符串文件= console.next(); QuizBowlRedo newGame =新QuizBowlRedo(第一,最后文件); //创建QuizBowl的新游戏
newGame.quiz(); //开始游戏
}
}
下面是我的对象类的一个构造函数。 QuestionMC,QuestionSA和QuestionTF扩展问题类:
公共QuestionSA(字符串问题,字符串questionType,INT点,弦乐答案){
超(问题,questionType,点);
this.answer =答案;
}
这是我从阅读文本文件:
3
TF 5
存在的不能飞的鸟。 (真假)
真正
MC 10
谁是美国在1991年的president?
6
理查德·尼克松
杰拉尔德·福特
吉米·卡特
罗纳德·里根
老布什
比尔·克林顿
Ë
SA 20
哪个城市主办2004年夏季奥运会?
雅典
我说的是在 readQuestion()
方法启动的一部分。我试图在地区与评论说对象添加到的ArrayList
读取一个....问题。迄今为止,它的未来了一个空的的ArrayList
。
-
ReadFile的()
的循环,直到qnum并调用readQuestion()
。但是,它不通过当前的问题数readQuestion()
。所以readQuestion()
总是从第一次启动? -
readQuestion()
被开扩输入文件(因此,可能阅读的第一个问题了一遍又一遍)。它可能是任务ReadFile的()
-
方法的第一行从标准输入读取。你可能意味着从gameFile扫描仪读取?
I'm trying to add different objects to an ArrayList
and it's not working. I'm not sure if it's because I'm adding objects incorrectly or if there's something else wrong.
Here's my code.
import java.util.*;
import java.io.*;
public class QuizBowl implements Quiz {
private Player player; // player object
private String file; // name of file
private int qNum; // number of questions player wants to answer
private int qNumFile; // number of questions in file
private ArrayList<Question> questionsArr; // holds Question objects
private boolean questionsAsked[]; // array of questions that were already asked
// Constructor
public QuizBowl(String fName, String lName, String file) throws FileNotFoundException {
player = new Player(fName, lName);
Scanner gameFile = new Scanner(new File(file));
qNum = numOfQuestionsToPlay();
qNumFile = maxNumQFile(gameFile);
questionsArr = new ArrayList<Question>();
readFile();
System.out.println(questionsArr);
questionsAsked = new boolean[qNumFile];
System.out.println(Arrays.toString(questionsAsked));
}
// asks user how many questions to ask
public int numOfQuestionsToPlay() {
Scanner console = new Scanner(System.in);
// CHECKS FOR VALID USER INPUT
boolean check = false;
do {
try {
System.out.print("How many questions would you like (out of 3)? ");
int answer = console.nextInt();
if(answer > 3) {
System.out.println("Sorry, that is too many.");
check = false;
}
else {
check = true;
}
}
catch(InputMismatchException e) {
System.out.println("Invalid input. Please try again.");
console.nextLine();
check = false;
}
}
while(check == false);
return qNum;
}
// figures out how many questions are in the file
public int maxNumQFile(Scanner gameFile) {
int num = gameFile.nextInt();
return num;
}
// LOOP FOR READING QUESTIONS
public void readFile() {
for(int i = 0; i < qNum; i++) {
readQuestion();
}
}
// READS QUESTION AFTER QUESTION AND ADDS TO THE ARRAYLIST OF QUESTIONS OBJECTS
public void readQuestion() {
Scanner console = new Scanner(System.in);
console.nextLine();
String[] line;
String question, questionType;
int points;
line = console.nextLine().split(" ");
questionType = line[0];
points = Integer.parseInt(line[1]);
question = console.nextLine();
if(questionType.equals("MC")) { // checks if question type is MC
questionsArr.add(readMC(questionType, question, points, console)); // adds MC question to array
}
else if(questionType.equals("SA")) { // checks if question type is SA
questionsArr.add(readSA(questionType, question, points, console)); // adds SA question to array
}
else { // checks if question type is TF
questionsArr.add(readTF(questionType, question, points, console)); // adds TF question to array
}
}
// READS ONE TF QUESTION
public static QuestionTF readTF(String questionType, String question, int points, Scanner console) { // returns new QuestionTF object
String ans = console.nextLine();
return new QuestionTF(question, questionType, points, ans);
}
// READS ONE SA QUESTION
public static QuestionSA readSA(String questionType, String question, int points, Scanner console) {
String ans = console.nextLine();
return new QuestionSA(question, questionType, points, ans); // returns new QuestionSA object
}
// READS ONE MC QUESTION
public static QuestionMC readMC(String questionType, String question, int points, Scanner console) {
int numChoices;
String[] choices;
String ans;
numChoices = Integer.parseInt(console.nextLine());
choices = new String[numChoices];
ans = console.nextLine();
for(int i = 0; i < numChoices ; i++) {
choices[i] = console.nextLine();
}
return new QuestionMC(question, questionType, points, choices, ans); // returns new QuestionMC object
}
// STARTS QUIZ
public void quiz() {
int qCount = 0;
int ranQ;
Scanner userInput = new Scanner(System.in);
String userAns;
Random r = new Random();
// RUNS QUIZ
while (qCount < qNum) {
ranQ = r.nextInt(qNumFile);
// CHECKS IF QUESTION HAS ALREADY BEEN ASKED
if (!checkDup(ranQ, questionsAsked)) {
questionsAsked[ranQ] = true;
Question question = questionsArr.get(ranQ); // GETS RANDOM QUESTION FROM ARRAY
question.printQuestion(); // prints question and points
userAns = userInput.next(); // retrieves answer from user
// CHECKS USER'S ANSWER
if(userAns.equals("SKIP")) {
System.out.println("You have chosen to skip this question.");
}
else {
checkAnswer(userAns, question, player);
}
qCount++;
System.out.println();
}
}
}
// CHECKS IF QUESTION HAS ALREADY BEEN ASKED
public boolean checkDup(int ranQ, boolean questionsAsked[]){
return questionsAsked[ranQ];
}
// CHECKS ANSWER AND ADDS POINTS
public void checkAnswer(String userAnswer, Question question, Player player) {
if(question.checkAnswer(userAnswer)) {
System.out.println("Correct you get " + question.getPoints());
player.setScore(question.getPoints());
}
else {
System.out.println("Incorrect, the answer was " + question.getAnswer() + "." +
" you lose " + question.getPoints() + ".");
player.setScore(question.getPoints() * -1);
}
}
// Executes program
public static void main(String[] args) throws FileNotFoundException {
Scanner console = new Scanner(System.in);
System.out.print("Please enter your first name: ");
String first = console.next();
System.out.print("Please enter your last name: ");
String last = console.next();
System.out.print("Please enter the game file name: ");
String file = console.next();
QuizBowlRedo newGame = new QuizBowlRedo(first, last, file); // creates new game of QuizBowl
newGame.quiz(); // starts game
}
}
Here is a constructor for one of my object classes. QuestionMC, QuestionSA, and QuestionTF extend the Question class:
public QuestionSA(String question, String questionType, int points, String answer) {
super(question, questionType, points);
this.answer = answer;
}
And here is the text file that I'm reading from:
3
TF 5
There exist birds that can not fly. (true/false)
true
MC 10
Who was the president of the USA in 1991?
6
Richard Nixon
Gerald Ford
Jimmy Carter
Ronald Reagan
George Bush Sr.
Bill Clinton
E
SA 20
What city hosted the 2004 Summer Olympics?
Athens
The part I'm talking about starts at the readQuestion()
method. And I'm trying to add objects to the ArrayList
in the areas with the comments saying "READS ONE .... QUESTION". So far, it's coming out with an empty ArrayList
.
readFile()
is looping until qnum and callingreadQuestion()
. However, it does not pass the "current" question number toreadQuestion()
. soreadQuestion()
always starts from the first?readQuestion()
is openning the input file (and thus, probably read the first question over and over again). it is probably the task ofreadFile()
The first line of the method reads from stdin. You probably meant to read from gameFile scanner?
这篇关于Java程序没有对象添加到ArrayList的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!