Java BufferedReader error: NullPointerException [duplicate] - java

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
I have a small assignment for uni which I seem to be stuck with. The application is suppose to be a quiz program which reads questions and answers from a text files and stores them like a flash card. My problem is that my buffered reader seems to be returning the nullPointer exception when it tries to read from the file. I'm unsure why this is. I will provide all code and highlight the error in bold. After doing a bit of debugging I found that the readLine method was returning null. Any thoughts? Thanks a lot. Error is at String[] line = getLine().split(":");
text file is in the format question:answer
import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;
public class Quiz {
private ArrayList<FlashCard> flashCards;
public static void main(String[] args){
Quiz quiz1 = new Quiz();
}
public Quiz(){
FlashCardReader cardReader = new FlashCardReader();
try {
if(cardReader.isReady()==true){
flashCards = cardReader.getFlashCards();
play();
}
} catch (IOException e) {
e.printStackTrace();
}
}
private void play(){
Scanner userInput = new Scanner(System.in);
String answer = userInput.nextLine();
for(FlashCard card: flashCards){
System.out.println(card.getQuestion());
System.out.println("********************");
sleep(10000);
System.out.println("Enter your answer:");
answer = userInput.nextLine();
if(card.getAnswer() == answer){
System.out.println("Correct.");
}else{
System.out.println("Incorrect. The correct answer is " + card.getAnswer() + ".");
}
}
}
private void sleep(int x){
try {
Thread.sleep(x);
} catch(InterruptedException ex) {
Thread.currentThread().interrupt();
}
}
}
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
public class FlashCardReader {
BufferedReader reader;
public FlashCardReader(){
try {
reader = new BufferedReader(new FileReader("Questions.txt"));
} catch (FileNotFoundException e) {
System.err.println(e.toString());
}
}
public String getLine() throws IOException{
return reader.readLine();
}
public Boolean isReady() throws IOException{
return reader.ready();
}
public ArrayList<FlashCard> getFlashCards(){
ArrayList<FlashCard> flashcards = new ArrayList<FlashCard>();
try {
for(int i = 1; i <= reader.lines().count(); i++){
**String[] line = getLine().split(":");**
System.out.println(line[0]);
flashcards.add(new FlashCard(line[0],line[1]));
}
} catch (IOException e) {
System.err.println(e);
e.printStackTrace();
}
return flashcards;
}
}
public class FlashCard {
private String question;
private String answer;
public FlashCard(String question, String answer){
this.question = question;
this.answer = answer;
}
public String getQuestion(){
return question;
}
public String getAnswer(){
return answer;
}
}

How about changing the for loop to while loop to avoid null condition. As you cannot be sure that your code starts from line one as you expect by assigning i to 1.
String lines ;
while((lines = getLine()) != null){
String[] lineArray = lines.split(":");
System.out.println(lineArray[0]);
flashcards.add(new FlashCard(lineArray[0],lineArray[1]));
}

Related

I wanto randomize my csv file for a quizz game [duplicate]

This question already has answers here:
How to shuffle an ArrayList [duplicate]
(2 answers)
Closed 1 year ago.
i have my quizz game reading a csv file to get the questions but i dont know how to randomize them for every time start the game i dont know if its possible with the code i have and i dont want to change to sql or sqllite because i already did this way and i want to finish like that, thats my code to read the file
import android.content.Context;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
public class CsvFileReader {
public ArrayList<Question> readFile(Context ctx){
ArrayList<Question> questions = new ArrayList<>();
InputStream inputStream = ctx.getResources().openRawResource(R.raw.question);
CSVFile csvFile = new CSVFile(inputStream);
List<String[]> scoreList = csvFile.read();
for (int i=1;i<scoreList.size();i++)
{
String[] strings = scoreList.get(i);
int questionId = 0;
String question = "";
int dificulty = 0;
int correctAnswer = 0;
String answer1 = "";
String answer2 = "";
String answer3 = "";
String answer4 = "";
int length = strings.length;
if (length>0){
try {
questionId = Integer.parseInt(strings[0]);
}catch (Exception ex){
}
}
if (length>1){
question = strings[1];
}
if (length>2){
try {
dificulty = Integer.parseInt(strings[2]);
}catch (Exception ex){
}
}
if (length>3){
try {
correctAnswer = Integer.parseInt(strings[3]);
}catch (Exception ex){
}
}
if (length>4){
answer1 = strings[4];
}
if (length>5){
answer2 = strings[5];
}
if (length>6){
answer3 = strings[6];
}
if (length>7){
answer4 = strings[7];
}
Question questionData = new Question(questionId,question,dificulty,correctAnswer,answer1,answer2,answer3,answer4);
questions.add(questionData);
}
return questions;
}
}
i want every time i start the quizz need to randomize the questions and down there is the code from the file
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
public class CSVFile {
InputStream inputStream;
public CSVFile(InputStream inputStream){
this.inputStream = inputStream;
}
public List read(){
List resultList = new ArrayList();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
try {
String csvLine;
while ((csvLine = reader.readLine()) != null) {
String[] row = csvLine.split(",");
resultList.add(row);
}
}
catch (IOException ex) {
throw new RuntimeException("Error reading: "+ex);
}
finally {
try {
inputStream.close();
}
catch (IOException e) {
throw new RuntimeException("Error while closing input stream: "+e);
}
}
return resultList;
}
}
if someone need more code to get in or whatever let me know i would appreciate the help.
You can use Collections.shuffle to randomize an arrayList. This function is in java.util.
Something like this:
import java.util.Collections;
...
public ArrayList<Question> readFile(Context ctx){
ArrayList<Question> questions = new ArrayList<>();
...
Collections.shuffle(questions);
return questions;
}
This will return a randomize ArrayList

Java program keep running, no compiler's error [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I'm trying to write a code for selecting features from a txt file.
i.e. size = 1.4356474
species = fw, wevb, wrg , gwe
....
this is the code I wrote so far:
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.text.ParseException;
import java.util.concurrent.ExecutionException;
public class Metodi {
public static void main (String[] args) {
String volume = findVolume();
System.out.println(volume);
}
public static String readSpecification() {
String spec = "";
// trying to read from file the specification...
try {
BufferedReader reader = new BufferedReader(new FileReader("Gemcitabine.txt"));
String line = reader.readLine();
while(line!=null) {
spec += line + "\n";
line = reader.readLine();
}
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}
return spec;
}
public static String findVolume () {
String res = "";
String vol = "volume";
try {
BufferedReader reader1 = new BufferedReader(new FileReader("Sample.txt"));
String line1 = reader1.readLine();
while(line1!=null) {
if(line1.toLowerCase().indexOf(vol) != -1) {
String[] str = line1.split("=");
res = str[1].split(" ")[0];
}
}
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}
return res;
}
}
It doesn't give me any compiler's error, but when I launch it, it keeps running and doesn't end.
Any help?
Your loop is not reading line after line, it needs to call read line on each iteration, it should be :
String line1 =;
while((line1 = reader1.readLine()) != null) {
if(line1.toLowerCase().indexOf(vol) != -1) {
String[] str = line1.split("=");
res = str[1].split(" ")[0];
}
}
In findVolume(), you check line1 != null in your while-condition.
You never change line1 within the loop. Thus, it will never be equal to null and the loop won't terminate.

Reading a .txt file that results in a stackoverflow error

Can someone please help me determine what I am doing wrong with my code. I am getting a stackoverflow error. At the end of my code I am using recursion and I don't have a base case to stop the program. It keeps looping and displaying my text file until I get a stackoverflow error.
public class Reader
{
public static String readFinalQuestionBank() throws Exception
{
File textFile = new File("C:\\Users\\Joseph\\Documents\\School Files - NHCC\\CSci 2002\\FinalQuestionBank_JosephKraemer.txt"); //file location
try
{
Scanner scan = new Scanner(textFile); //Scanner to import file
while(scan.hasNextLine()) //Iterator - while file has next line
{
String qBank = scan.nextLine(); //Iterator next line
String[] tempArray = qBank.split("::"); //split data via double colon
System.out.println(qBank); //print data line
}
scan.close(); //close scanner
}
catch(FileNotFoundException e)
{
e.printStackTrace();
}
return readFinalQuestionBank(); //use of Recursion
}//end method readFinalQuestionBank
}//end class Reader
if your main objective is to read the whole input file by implementing recursivity take a look at the following example, it replaces the while statement with a recursive method call.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Reader
{
public static String readFinalQuestionBank() throws Exception
{
File textFile = new File("C:\\Users\\Diego\\Documents\\sandbox\\input.txt");
String output = "";
try
{
Scanner scan = new Scanner(textFile);
output = readLineRecursively(scan);
scan.close();
}
catch(FileNotFoundException e)
{
e.printStackTrace();
}
return output;
}
private static String readLineRecursively(Scanner scan){
if(!scan.hasNextLine()){
return "";
}
String qBank = scan.nextLine();
return qBank + "\n" + readLineRecursively(scan);
}
public static void main(String[] args){
try {
System.out.println(readFinalQuestionBank());
} catch (Exception e) {
e.printStackTrace();
}
}
}

Fixing a Null Pointer Exception in Java [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 8 years ago.
I'm learning about BufferedReaders and a few other classes and am making a small program that takes a text file with information about courses I've taken and calculates my GPA. Here's what I have so far:
import java.util.ArrayList;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
class GradeFormatter {
public static ArrayList<String[]> courses;
public static double unitsAttempted;
public static double unitsPassed;
public static double gradePoints;
public static double gpa;
public static void main(String[] args) {
try {
FileReader fileReader = new FileReader("grades.txt");
BufferedReader reader = new BufferedReader(fileReader);
while (true) {
String line = reader.readLine();
if (line == null) {
break;
} else {
processLine(line);
}
}
reader.close();
} catch (IOException e) {
System.out.println("File does not exist.");
}
}
public static void processLine(String line) {
String[] newCourse = line.split("\\t");
courses.add(newCourse);
}
}
I'm getting the following output when I try to run the program:
Exception in thread "main" java.lang.NullPointerException
at GradeFormatter.processLine(GradeFormatter.java:34)
at GradeFormatter.main(GradeFormatter.java:23)
Could anyone help me out with why I'm getting this null pointer exception? I cannot seem to figure out where it's coming from.
You should initilize the ArrayList courses ArrayList<String[]> courses = new ArrayList<String[]>()

Java: Uncaught Exception Error?

I submitted this code to the KATTIS online code tester. It's supposed to return the difference of two numbers that have been given repeatedly until it reaches an EOF. It works just fine in eclipse, but KATTIS says that "An exception was not caught". I was hoping for some help as to what exception has not been caught.
The imports and class "Kattio" were provided so the input and output would always work with the online code system.
import java.util.StringTokenizer;
import java.io.BufferedReader;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.OutputStream;
class Kattio extends PrintWriter {
public Kattio(InputStream i) {
super(new BufferedOutputStream(System.out));
r = new BufferedReader(new InputStreamReader(i));
}
public Kattio(InputStream i, OutputStream o) {
super(new BufferedOutputStream(o));
r = new BufferedReader(new InputStreamReader(i));
}
public boolean hasMoreTokens() {
return peekToken() != null;
}
public int getInt() {
return Integer.parseInt(nextToken());
}
private BufferedReader r;
private String line;
private StringTokenizer st;
private String token;
private String peekToken() {
if (token == null)
try {
while (st == null || !st.hasMoreTokens()) {
line = r.readLine();
if (line == null) return null;
st = new StringTokenizer(line);
}
token = st.nextToken();
} catch (IOException e) { }
return token;
}
private String nextToken() {
String ans = peekToken();
token = null;
return ans;
}
}
public class Hello {
public static void main(String[] args) {
Kattio io = new Kattio(System.in, System.out);
while (io.hasMoreTokens()){
int n1 = io.getInt();
int n2 = io.getInt();
if (n1>n2){
io.println(n1-n2);
}
else if (n2>n1){
io.println(n2-n1);
}
else {
io.println("0");
}
}
io.close();
}
}
just a guess.
Look for exception in your code with different types of data. If a line with non integer your program will terminate. It should probably look for next token?
Please modify your main() by adding try/catch like so:
public static void main(String[] args) {
try {
Kattio io = new Kattio(System.in, System.out);
while (io.hasMoreTokens()){
int n1 = io.getInt();
int n2 = io.getInt();
if (n1>n2){
io.println(n1-n2);
}
else if (n2>n1){
io.println(n2-n1);
}
else {
io.println("0");
}
}
io.close();
} catch(Exception e) { e.printStackTrace(); }
}
Normally you would want more localized exception handling but this will at least allow you to copy-paste us the stacktrace so we can see it.
I am unfamiliar with the Kattis online code tester but assume it checks for unchecked exceptions that may be thrown (an uncaught checked exception would cause the code not to compile). I can't see anywhere in the code that checks that the next token is an Integer, so if Integer.parseInt tries to parse something which isn't an integer, it will throw a NumberFormatException.
Depending on the audience for your application, you could leave this as it is (if the audience is java developers who will understand that exception) or catch it rethrow something more user-friendly (if they are not).
public int getInt() {
// not tested
int nextInt;
try {
nextInt = Integer.parseInt(nextToken());
} catch (NumberFormatException nfe) {
throw new RuntimeException("Invalid number in file");
}
return nextInt;
}
Presumably though, the code tester would still complain though as it's throwing another (more user-friendly) exception :-)

Categories

Resources