2016-03-13 5 views
0

Я пытаюсь добавить разные объекты в ArrayList, и это не работает. Я не уверен, что это потому, что я добавляю объекты неправильно или если что-то не так.Java-программа не добавляет объекты в ArrayList

Вот мой код.

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 
    } 
} 

Вот конструктор для одного из моих классов объектов. QuestionMC, QuestionSA и QuestionTF расширить класс Вопрос:

public QuestionSA(String question, String questionType, int points, String answer) { 
     super(question, questionType, points); 
     this.answer = answer; 
    } 

А вот текстовый файл, который я читаю из:

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 

Часть, о которой я говорю начинается в методе readQuestion() , И я пытаюсь добавить объекты к ArrayList в областях с комментариями, говорящими «ЧИТАЕТ ОДИН .... ВОПРОС». Пока что он выходит с пустым ArrayList.

+0

Какая ошибка вы получаете? Всегда включайте ошибку, которую вы получаете. –

+0

Нет всплывающей ошибки. программа компилируется. Моя единственная проблема заключается в добавлении объектов в ArrayList. – Jasmine

+0

Какая связь между Вопросом, QuestionTF, QuestionSA, QuestionMC? – Learner

ответ

0
  1. readFile() не зацикливается до qnum и вызова readQuestion(). Однако он не передает «текущий» номер вопроса до readQuestion(). так readQuestion() всегда начинается с первого?

  2. readQuestion() открывает входной файл (и, следовательно, возможно, первый и снова вопрос снова и снова). это, вероятно, задача readFile()

  3. Первая строка метода считывается из stdin. Вы, вероятно, хотели читать с сканера gameFile?

+0

Я немного смущен в ваших первых двух комментариях. Для первого, вы говорите, что я должен сделать что-то вроде 'readQuestion (i)'? Я не уверен, что это такое, если вы передадите «текущий» номер вопроса. Кроме того, я не знаю, что вы имеете в виду, когда говорите, что 'readQuestion()' открывает входной файл. – Jasmine

+0

задайте себе этот вопрос - как readQuestion собирается «знать», какой вопрос он читает? когда он называется второй раз (предположительно, чтобы прочитать второй вопрос), как он должен знать, что это второй раз, когда он называется? –

+0

, который должен быть ошибкой в ​​моей логике, я подумал, что 'Scanner gameFile' будет содержать указатель, где бы он ни находился. Таким образом, указатель будет непрерывно перемещаться по файлу через цикл. – Jasmine

Смежные вопросы