I'm having trouble figuring out what's wrong with my java code. I am creating a Trivia Game that reads in the question ID, question, answer, and answer point value from a dat file.
I've tried all sorts of things, but am getting the same NumberFormatException
.
Below is an example of how the dat file is setup: 10 questions total
1: 01 2: What is light as a feather, but even the strongest man cannot hold it more than a few minutes? 3: His breath 4: 3
Game.java
import java.util.*;
import java.io.*;
public class Game {
// Instance Variables
private QuestionBank[] questions;
private int numQuestions;
private int questionNumber;
private int playerScore;
// Constructor
public Game()
{
QuestionBank[] questions = new QuestionBank[10];
numQuestions = 0;
questionNumber = 0;
playerScore = 0;
}
public Game(FileInputStream questionsFile)
{
BufferedReader br = new BufferedReader(new InputStreamReader(questionsFile));
String stringLine = null;
int i = 0;
try
{
while((stringLine = br.readLine()) != null)
{
QuestionBank quest = new QuestionBank();
quest.setQuestionID(Integer.valueOf(br.readLine())); //ERROR OCCURS HERE
quest.setQuestion(br.readLine());
quest.setAnswer(br.readLine());
quest.setPointValue(Integer.valueOf(br.readLine()));
questions[i] = quest;
i++;
stringLine = null;
}
br.close();
}
catch (IOException e)
{
System.out.println("Uh oh. Exception caught.");
}
this.questionNumber = 0;
/*Scanner questionsFileScanner = new Scanner(questionsFile);
questions = new QuestionBank[5];
while(questionsFileScanner.hasNextLine())
{
for(int i = 0; i < 4; ++i)
{
questions[i] = new QuestionBank();
questions[i].setQuestion(questionsFileScanner.nextLine());
}
}*/
}
//Accessors and Mutators
public int getNumQuestions()
{
return numQuestions;
}
public int getQuestionNumber()
{
return questionNumber;
}
public int getPlayerSocre()
{
return playerScore;
}
public boolean checkAnswer(String answer)
{
if(answer.contentEquals(questions[questionNumber].getAnswer()) == true)
{
playerScore += questions[questionNumber].getPointValue();
++questionNumber;
return true;
}
else
{
return false;
}
}
public String getNextQuestion()
{
return questions[questionNumber].getQuestion();
}
public String toString()
{
String outputString = "";
for (int i = 0; i < questionNumber; ++i)
{
outputString = questions[i].toString();
}
return outputString;
}
}
Exception in thread "main" java.lang.NumberFormatException: For input string: "What is light as a feather, but even the strongest man cannot hold it more than a few minutes?"
at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.base/java.lang.Integer.parseInt(Integer.java:652)
at java.base/java.lang.Integer.valueOf(Integer.java:983)
at project7.Game.<init>(Game.java:41)
at project7.RunGame.main(RunGame.java:41)