Я написал следующий метод, который показывает количество правильных, неправильных и пустых ответов, которые вы имеете на экзамен. Проблема в том, что сверхурочное время я пытаюсь скомпилировать файл, я получаю Null Pointer Exception
Я попытался перемещаться по переменным и повторно инициализировать их, но безуспешно.Исключение Null Pointer (Java) [EDIT!]
Как исправить проблему. (Сожалею об этом, я клянусь богом, что это полный код :)
import java.io.*;
import java.util.Scanner;
import java.lang.*;
public class Exam
{
public static int numOfQ; //Number of Questions
public static int numOfS; //Number of Answers
public static String answers; //Correct Answers
public static String answersFile; //Student Answers File
public static BufferedReader br;
public static void Start()
{
numOfQ = 10;
System.out.println();
System.out.println("Welcome to Exam Analysis. Let’s begin ...");
System.out.println();
System.out.println();
System.out.println("Please type the correct answers to the exam questions,");
System.out.print("one right after the other: ");
Scanner scan = new Scanner(System.in);
answers = scan.nextLine();
System.out.println("What is the name of the file containing each student's");
System.out.print("responses to the " + numOfQ + " questions? ");
answersFile = scan.nextLine();
System.out.println();
}
public static void Responses() throws FileNotFoundException, IOException
{
br = new BufferedReader(new FileReader(answersFile));
String line = null;
while ((line = br.readLine()) != null)
{
numOfS++;
System.out.println("Student #" + numOfS+ "\'s responses: " + line);
}
System.out.println("We have reached “end of file!”");
System.out.println();
System.out.println("Thank you for the data on " + numOfS + " students. Here is the analysis:");
}
public static void Analysis1() throws FileNotFoundException, IOException
{
System.out.println("Student # Correct Incorrect Blank");
System.out.println("~~~~~~~~~ ~~~~~~~ ~~~~~~~~~ ~~~~~");
int i = 0;
for (int start = 0; start < numOfS; start++)
{
i++;
int correct = 0;
int incorrect = 0;
int blank = 0;
if (br.readLine().charAt(start) == (answers.charAt(start)))
{
correct++;
}
else {
if (br.readLine().charAt(start) == ' ')
{
blank++;
}
else
{
incorrect++;
}
System.out.printf("%2d %2d %2d %2d", i, correct, incorrect, blank);
}
}
}
public static void Analysis2() throws FileNotFoundException, IOException
{
System.out.println("QUESTION ANALYSIS (* marks the correct response)");
System.out.println("~~~~~~~~~~~~~~~~~");
for (int i = 1; i <= numOfQ; i++)
{
int a = 0;
int b = 0;
int c = 0;
int d = 0;
int e = 0;
System.out.println("Question #" + i + ":");
if (br.readLine().charAt(i - 1) == 'A')
{
a++;
}
else if (br.readLine().charAt(i - 1) == 'B')
{
b++;
} else if (br.readLine().charAt(i - 1) == 'C')
{
c++;
} else if (br.readLine().charAt(i - 1) == 'D')
{
d++;
} else if (br.readLine().charAt(i - 1) == 'E')
{
e++;
}
}
}
public static void main(String[] args) throws FileNotFoundException, IOException {
Start();
Responses();
Analysis1();
}
}
Это то, что консоль дала мне во время исполнения:
Исключение в потоке «основной» Java .lang.NullPointerException
на Exam.Analysis2 (Exam.java:93)
на Exam.main (Exam.java:116)
Опубликовать достаточно для того, чтобы воспроизвести. –
Сообщите мне об ошибке. – HyperZ
'br' может быть' null', 'readLine()' может возвращать 'null',' answers' может быть 'null'. Я предлагаю вам [взглянуть на трассировку стека и определить строку кода, где это происходит] (http://stackoverflow.com/questions/3988788/what-is-a-stack-trace-and-how-can -i потребительной это в отладке-мое-приложение-ошибки). Также вы должны использовать фигурные скобки для операторов if/else, что улучшит читаемость. –