2013-08-20 2 views
0

Я пишу код, чтобы помочь мне научить меня, как код в java, и я использовал массивы. У меня ошибка, и я не могу понять, почему это происходит. Кодекс:Не удается найти ошибку в коде

import java.util.Scanner; 
public class pubQuizArray { 
private static Scanner kb = new Scanner (System.in); 
static String[] questions; 
static String[][] answers; 
static char[] realAnswers; 
static char ans; 
static char yn; 
static int questionNum; 
static int questionNumArray; 
static int numQ; 
static int score = 0; 

public static void writeQuiz() 
{ 
    getQNum(); 
    getQ(); 
} 

public static void getQNum() 
{ 
    System.out.println("How many Questions?"); 
    numQ = kb.nextInt(); 
    questions = new String[numQ]; 
} 

public static void getAns() 
{ 
    questionNumArray = questionNum - 1; 
    answers = new String[numQ][]; 
    System.out.println("What are the answers?"); 

    System.out.println("a: "); 
    answers[questionNumArray][0] = kb.nextLine(); 

    System.out.println("b: "); 
    answers[questionNumArray][1] = kb.nextLine(); 

    System.out.println("c: "); 
    answers[questionNumArray][2] = kb.nextLine(); 

    System.out.println("d: "); 
    answers[questionNumArray][4] = kb.nextLine(); 

    realAnswers = new char[numQ]; 
    System.out.println("What is the correct Answer?"); 
    realAnswers[questionNum] = kb.next().charAt(0); 

} 

public static void getQ() 
{ 
    questionNum = 0; 
    System.out.println("What is the First Question?"); 
    questions[questionNum] = kb.nextLine(); 
    getAns(); 
    questionNum ++; 
    while(questionNum < numQ) 
    { 
     System.out.println("What is the next Question?"); 
     questions[questionNum] = kb.nextLine(); 
     getAns(); 
     questionNum ++; 
    } 
} 

public static void askQ() 
{ 
    questionNum = 0; 
    while(questionNum < numQ) 
    { 
     System.out.println("Q1: " + questions[questionNum]); 

     System.out.println("a: " + answers[questionNum][0]); 
     System.out.println("b: " + answers[questionNum][1]); 
     System.out.println("c: " + answers[questionNum][2]); 
     System.out.println("d: " + answers[questionNum][3]); 

     ans = kb.next().charAt(0); 
     if(ans == realAnswers[questionNum]) 
     { 
      System.out.println("That was correct"); 
      score ++; 
     } 
    } 
} 

public static void menu() 

{ 
    System.out.println("Would you like to write a new Quiz? y/n"); 
    yn = kb.next().charAt(0); 
    while(yn == 'y') 
    { 
     writeQuiz(); 
     System.out.println("Would you like to play the Quiz? y/n"); 
     yn = kb.next().charAt(0); 
     while(yn == 'y') 
     { 
      askQ(); 
      System.out.println("Would you like to play again? y/n"); 
      yn = kb.next().charAt(0); 
     } 
    } 
} 

public static void main(String[] args) 
{ 
    menu(); 
} 
} 

Ошибка заключается в следующем:

Would you like to write a new Quiz? y/n 
y 
How many Questions? 
10 
What is the First Question? 
What are the answers? 
a: 
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1 
    at pubQuizArray.getAns(pubQuizArray.java:34) 
    at pubQuizArray.getQ(pubQuizArray.java:56) 
    at pubQuizArray.writeQuiz(pubQuizArray.java:17) 

Заранее спасибо за любую помощь, которую вы можете дать. Пожалуйста, имейте в виду, что это всего лишь пробная программа и что я все еще изучаю Java.

ОК У меня есть еще одна проблема на этот раз он говорит:

Would you like to write a new Quiz? y/n 
y 
How many Questions? 
1 
What is the First Question? 
and 
What are the answers? 
a: a 
Exception in thread "main" java.lang.NullPointerException 
    at pubQuizArray.getAns(pubQuizArray.java:34) 
    at pubQuizArray.getQ(pubQuizArray.java:57) 
    at pubQuizArray.writeQuiz(pubQuizArray.java:17) 
    at pubQuizArray.menu(pubQuizArray.java:96) 
    at pubQuizArray.main(pubQuizArray.java:110) 

и я уже обновил другой предыдущий код.

ответ

3

В этот момент внутри getAns()

questionNumArray = questionNum - 1; 
answers = new String[numQ][]; 
System.out.println("What are the answers?"); 

System.out.println("a: "); 
answers[questionNumArray][0] = kb.nextLine(); 

questionNumArray содержит значение -1, которое является недействительным индекс для массива.

Это происходит от

public static void getQ() 
{ 
    questionNum = 0; // set to 0 
    System.out.println("What is the First Question?"); 
    questions[questionNum] = kb.nextLine(); 
    getAns(); // still 0 
    questionNum ++; // too late 
    ... 
} 

Edit

NPE вы получаете сводится к

System.out.println("a: "); 
answers[questionNumArray][0] = kb.nextLine(); 

вы не инициализирован answers[questionNumArray] так null. Сделайте следующее сначала

answers[questionNumArray] = new String[someSize]; // someSize should probably be 5 looking at your code 
+0

ОК спасибо. У меня другая проблема, и я получаю еще одну проблему. – user2682894

+0

@ user2682894 Добро пожаловать, но мы не являемся фабрикой отладки. Используйте отладчик, когда вы получаете такие исключения. –

+0

Я не могу найти его на eclipse, и дополнительное объяснение полезно для других проектов. – user2682894

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