Compilation error: type mismatch [closed] - java

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Changed my code since I should protect my code from students against plagiarism.
I got this error when I tried to compile my code:
Unresolved compilation problem:
Type mismatch: cannot convert from Object to Entry
at SchoolManager.listGrade(SchoolManager.java:49)
at SchoolManager.main(SchoolManager.java:30)
mainClass.java
public class mainClass {
static Scanner scanner = new Scanner(System.in);
static ArrayList<C> c = new ArrayList();
static ArrayList<Object> ob = new ArrayList();
public static void main(String [] args){
while(true){
System.out.println("----------------------------------------------------------------------------");
System.out.println("New:1 Add:2 ListC:3 ListOb:4 AddE:5 ListE:6");
System.out.println("----------------------------------------------------------------------------");
System.out.print(">> ");
String option = scanner.nextLine();
if(option.equals("0")){
System.out.println(c.size()+" "+ob.size()+" ");
System.out.println("Bye");
break;
}else if(option.equals("1")){
c.add(createC());
}else if(option.equals("2")){
ob.add(createOb());
}else if(option.equals("3")){
listC();
}else if(option.equals("4")){
listOb();
}else if(option.equals("5")){
addE();
}else if(option.equals("6")){
listE();
}else{
System.out.println(" ");
}
}
}
private static void listE() {
System.out.print("");
String ob1 = scanner.nextLine();
Object ob = findOb(ob1);
if(ob==null){
System.out.println(" ");
}else{
System.out.println(" ");
System.out.println(ob);
System.out.println(" ");
for(int i=0;i<ob.getE().size();i++){ // this part is a problem.
Entry e = ob.getE().get(i); // this part is a problem.
System.out.println(e.getC()+"\t"+ge.getT()+"\t"+ge.getE());
}
}
}
private static void addE() {
System.out.print(" ");
String ob1 = scanner.nextLine();
Object ob = findOb(ob1);
if(ob==null){
System.out.println("Could not be found...");
}else{
addE(ob);
}
}
private static Object findOb(String ob1) {
for(int i=0;i<ob.size();i++){
if(ob.get(i).getID().equals(ob1)){
return ob.get(i);
}
}
return null;
}
private static void addE(Object ob) {
System.out.print("? ");
String c_id = scanner.nextLine();
C c = findC(c_id);
if(c==null){
System.out.println("Could not be found...");
}else{
System.out.print("T? ");
String t = scanner.nextLine();
System.out.print("E? ");
String ee = scanner.nextLine();
ob.AddE(new Entry(c,t,ee));
}
}
private static C findC(String c_id) {
for(int i=0;i<c.size();i++){
if(c.get(i).getID().equals(c_id)) return c.get(i);
}
return null;
}
private static void listOb() {
for(int i=0;i<ob.size();i++){
System.out.println(ob.get(i));
}
System.out.println();
}
private static void listC() {
for(int i=0;i<c.size();i++){
System.out.println(c.get(i));
}
System.out.println();
}
private static Object createObject() {
System.out.print("S? ");
String id = scanner.nextLine();
System.out.print("N? ");
String n = scanner.nextLine();
System.out.print("S? ");
String s = scanner.nextLine();
return new Student(id,n,s);
}
private static C createC() {
System.out.print("C? ");
String id = scanner.nextLine();
System.out.print("Ct? ");
String Ct = scanner.nextLine();
return new Course(id,Ct);
}
}
Object.java:
public class Object {
public String ID;
public String n;
public String s;
public ArrayList<C> c;
public ArrayList<Ob> s;
public ArrayList<Entry> e;
public Object() {
}
public Object(String id, String n, String s) {
this.ID = id;
this.n = n;
this.s = s;
c= new ArrayList<C>();
ob= new ArrayList<Ob>();
e= new ArrayList<Entry>();
}
public String getId() {
return ID;
}
public String getN() {
return n;
}
public String getS() {
return s;
}
public String getID() {
return getId();
}
public void AddE(Entry e) {
e.add(Entry); //this part is a problem.
}
public ArrayList<Object> getE() {
return ob; //this part is a problem.
}
public String toString() {
String result = ID + " " + n + " " + s;
for(int i=0; i < c.size(); i++) {
result += c.get(i).toString();
result += "\n";
}
return result;
}
}
C.java:
import java.util.ArrayList;
public class C {
String co;
String t1;
public ArrayList<Ob> ob;
public C(String id, String t1) {
co = id;
this.t1 = t1;
ob = new ArrayList<Object>();
}
public String getCo() {
return co;
}
public String getT1() {
return t1;
}
public String getID() {
return getCo();
}
public String toString() {
String result = co + " " + t1;
for(int i=0; i < ob.size(); i++) {
result += ob.get(i).toString();
result += "\n";
}
return result;
}
}
Entry.java:
public class Entry {
public C c;
public String t;
public String g;
public ArrayList<Ob> g;
public Entry(C c, String term, String gr) {
c=c;
t=t;
gr=gr;
g = new ArrayList<Ob>();
}
public Course getC() {
return c;
}
public String getE() {
return g;
}
public String getT() {
return t;
}
public String toString() {
String result = c+ " " + t+ " " + g;
for(int i=0; i < gr.size(); i++) {
result += gr.get(i).toString();
result += "\n";
}
return result;
}
}
How can I solve this error?

This is the error it is talking about:
GradeEntry ge = student.getGrades().get(i);
Says can't convert from Student to GradeEntry, so I suspected getGrades was actually returning Students and yes that is the case:
public ArrayList<Student> getGrades() {
return students; //this part is a problem.
}
I think you meant to return grades:
public ArrayList<Grade> getGrades() {
return gr;
}

Related

Return user input into setter function

I have been working on an assignment and i am stuck at here. Basically i have 1 class which defines all functions and members.
And another class to initialize and manipulate objects.
Here is my first class code.
public class cyryxStudent_association {
String studentID, studentName, studentCourse_level, studentTitle;
int course_completed_year;
static double registration_fee;
double activity_fee;
double total_amt;
//Default constructor
cyryxStudent_association ()
{
studentID = "Null";
studentName = "Null";
studentCourse_level = "Null";
studentTitle = "Null";
course_completed_year = 0;
}
//Parameterized Constructor
cyryxStudent_association (String id, String name, String course_level, String title, int ccy)
{
this.studentID = id;
this.studentName = name;
this.studentCourse_level = course_level;
this.studentTitle = title;
this.course_completed_year = ccy;
}
//Getters
public String getStudentID ()
{
return studentID;
}
public String getStudentName ()
{
return studentName;
}
public String getStudentCourse_level ()
{
return studentCourse_level;
}
public String getStudentTitle ()
{
return studentTitle;
}
public int getCourse_completed_year ()
{
return course_completed_year;
}
public double getRegistration_fee ()
{
return registration_fee;
}
public double getActivity_fee ()
{
return findActivity_fee(registration_fee);
}
public double getTotal_amt ()
{
return total_amt(registration_fee, activity_fee);
}
//Setters
public void setStudentID (String id)
{
studentID = id;
}
public void setStudentName (String name)
{
studentName = name;
}
public void setStudentCourse_level (String course_level)
{
studentCourse_level = course_level;
}
public void setStudentTitle (String title)
{
studentTitle = title;
}
public void setCourse_completed_year (int ccy)
{
course_completed_year = ccy;
}
//Find registration fee method
public static double findRegistration_fee (String course_level)
{
if (course_level.equalsIgnoreCase("Certificate"))
{
registration_fee = 75;
}
else if (course_level.equalsIgnoreCase("Diploma"))
{
registration_fee = 100;
}
else if (course_level.equalsIgnoreCase("Degree"))
{
registration_fee = 150;
}
else if (course_level.equalsIgnoreCase("Master"))
{
registration_fee = 200;
}
return registration_fee;
}
//Find activity method
public static double findActivity_fee (double registration_fee)
{
return registration_fee * 0.25;
}
//Find total amount
public static double total_amt (double registration_fee, double activity_fee)
{
return registration_fee + activity_fee;
}
//To string method
public String toString ()
{
return "ID: "+getStudentID()+"\nName: "+getStudentName()+"\nCourse Level:
"+getStudentCourse_level()+"\nTitle: "+getStudentTitle()+"\nCourse Completed Year:
"+getCourse_completed_year()+"\nRegistration Fee: "+getRegistration_fee()+"\nActivity Fee:
"+getActivity_fee()+"\nTotal Amount: "+getTotal_amt ();
}
}
And here is my second class code.
import java.util.Scanner;
public class test_cyryxStudent_association {
public static void main (String[] args)
{
Scanner sc = new Scanner (System.in);
int num, i;
System.out.println("Welcome!");
System.out.println("\nEnter the number of students: ");
num = sc.nextInt();
sc.nextLine();
cyryxStudent_association Std[] = new cyryxStudent_association[num];
for (i = 0; i < Std.length; i++)
{
System.out.println("\nEnter ID: ");
Std[i].setStudentID(sc.nextLine());
System.out.println("Enter Name: ");
Std[i].setStudentName(sc.nextLine());
System.out.println("Enter Course Level [Certificate, Diploma, Degree, Master]: ");
Std[i].setStudentCourse_level(sc.nextLine());
System.out.println("Enter Title: ");
Std[i].setStudentTitle(sc.nextLine());
Std[i].getRegistration_fee();
Std[i].getActivity_fee();
Std[i].getTotal_amt();
}
for (i = 0; i < Std.length; i++)
{
System.out.println("\nStudent " + i + 1 + " Information");
System.out.println("===================================");
Std[i].toString();
}
sc.close();
}
}
I get an error when values in the for loop. Can someone help me? I'm pretty new to programming and studying java for 2 months now. What am i doing wrong?
Here is my objectives.
Create an array of objects and get user input for number of objects to be manipulated.
Read and display array of object values.
Thank you!
You have to initialize the objects of your array.
After the line:
cyryxStudent_association Std[] = new cyryxStudent_association[num];
do a for loop like:
for(i = 0; i<std.length; i++){
std[i] = new cyryxStudent_association();
}

Any reason why I can't create a class? I'm trying to have a Animal array to hold different animals

I am trying to create a animal array to try and hold the information of different types of animals/owners. Been trying to solve this for 2 hours reading the book but nothing is working. Can anyone point me to the right direction? Also how would I go about importing information from a URL to a array?
import java.net.URL;
import java.math.BigInteger;
import java.net.URL;
import java.net.HttpURLConnection;
import static java.util.Arrays.sort;
public class janesj_Program5 {
public static void main(String[] args) {
Animal[] j = new Animal[1];
storeFile(j);
sort(j);
printArray(j);
}
public static class Animal {
String OwnerName;
int birthYear;
public int billBalance;
String Species;
String feature;
public Animal() {}
public Animal(String OwnerName,int birthYear,int billBalance,String Species,String feature) {
this.OwnerName = OwnerName;
this.birthYear = birthYear;
this.billBalance = billBalance;
this.Species = Species;
this.feature = feature;
}
public int getBalance() {
return billBalance;
}
public String toString() {
return OwnerName + "\t" + birthYear + "\t" + getBalance() + "\t" + Species + "\t" + feature;
}
}
public static void storeFile(Animal[] x) {
String URLString = "http://yoda.kean.edu/~pawang/CPS2231/Program5_veterinarian_input.txt";
try {
java.net.URL url = new java.net.URL(URLString);
int count = 0;
Scanner input = new Scanner(url.openStream());
while(input.hasNext()) {
String line = input.nextLine();
count+= line.length();
x = new Animal[count];
}
}catch(java.net.MalformedURLException ex){
System.out.println("Invalid URL");
}
catch(java.io.IOException ex) {
System.out.println("I/O Errors: no such file");
}
}
public static class sorts extends Animal implements Comparator<Animal> {
public int compare(Animal a, Animal b) {
return a.getBalance() - b.getBalance();
}
}
public static void printArray(Animal[] x) {
System.out.println("\t Veterinarian Services Report \t Page:1");
System.out.println(" ==================================");
System.out.println("No\tOwner Name\tYear\tBalance\tSpecies\tLegs\tFeature");
System.out.println("== ==================== ==== ============ ============ ============");
for(int i = 1; i<=x.length;i++) {
System.out.println(i + " " + x.toString());
}
}
}
As so kindly pointed out by MTilsted you really should have your Animal class within its own .java file.
If you plan to create an array of Animal objects where the data to fill those objects is coming from a data file then you need to realize that arrays are of a fixed size, they can't just grow on a whim (at least not without more coding). You would need to know how may animals are contained within the data file so as to properly size your Animal array. Your in luck, by the look of it your data file contains the number of animals within the first line of the file (which needs to be ignored when reading in the actual animal data).
First, make sure the file actually exist. No sense going through heartache if it's not even there or there is something wrong with the connection to its' location. Once done, you can declare and initialize your Animals array to the proper size so as to handle all the data rows you are about to re-read into the array.
Below is your code to demonstrate how this can be accomplished.
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Scanner;
public class AnimalCare {
static Animals[] animals; // Declare The Anmimal Array as a class member variable
public static void main(String[] args) {
try {
URL url = new URL("http://yoda.kean.edu/~pawang/CPS2231/Program5_veterinarian_input.txt");
int lines = 0;
// Get the number of lines in file
try (Scanner s = new Scanner(url.openStream())) {
String firstFileLine = "";
while (firstFileLine.equals("")) {
firstFileLine = s.nextLine().trim();
if (!firstFileLine.equals("")) {
lines = Integer.parseInt(firstFileLine);
}
}
}
catch (IOException ex) {
String msg = "";
if (!ex.getMessage().equals(url.toString())) {
msg = "No Network Connection!";
}
else {
msg = "File Not Found! - " + ex.getMessage();
}
System.err.println(msg);
}
// Declare our Animals Array.
animals = new Animals[lines];
// Re-read the data file on network...
try (Scanner s = new Scanner(url.openStream())) {
int i = 0;
String dataLine;
s.nextLine(); // Skip the first line of file!
while (s.hasNextLine()) {
dataLine = s.nextLine().trim();
// Skip blank lines (if any)
if (dataLine.equals("")) {
continue;
}
String[] dataParts = dataLine.split("\\s+");
animals[i] = new Animals(dataParts[0],
Integer.parseInt(dataParts[1]),
Integer.parseInt(dataParts[2]),
dataParts[3],
dataParts[4]);
i++; // Increment i to create the next index value for array
}
// The Animals array is now filled with network file data
}
catch (IOException ex) {
String msg = "";
if (!ex.getMessage().equals(url.toString())) {
msg = "No Network Connection!";
}
else {
msg = "File Not Found! - " + ex.getMessage();
}
System.err.println(msg);
}
}
catch (MalformedURLException ex) {
System.err.println(ex.getMessage());
}
// Display the Animals array within the Console Window...
for (int i = 0; i < animals.length; i++) {
System.out.println(animals[i].toString());
}
}
}
And the Animals Class:
import java.util.Arrays;
public class Animals {
private String OwnerName;
private int birthYear;
private int billBalance;
private String Species;
private String feature;
//----------------- Constructors -------------------
public Animals() { }
public Animals(String OwnerName, int birthYear, int billBalance, String Species, String feature) {
this.OwnerName = OwnerName;
this.birthYear = birthYear;
this.billBalance = billBalance;
this.Species = Species;
this.feature = feature;
}
public Animals(Object[] data) {
if (data.length != 5 || !(data[0] instanceof String) ||
!(data[1] instanceof Integer) || !(data[2] instanceof Integer) ||
!(data[3] instanceof String) || !(data[4] instanceof String)) {
throw new IllegalArgumentException("Error in Animals Constructor data array! "
+ "Insufficiant data or invalid data element!" + System.lineSeparator() +
Arrays.deepToString(data));
}
this.OwnerName = data[0].toString();
this.birthYear = (int) data[1];
this.billBalance = (int) data[2];
this.Species = data[3].toString();
this.feature = data[4].toString();
}
//---------------------------------------------------
public int getBalance() {
return billBalance;
}
public String getOwnerName() {
return OwnerName;
}
public void setOwnerName(String OwnerName) {
this.OwnerName = OwnerName;
}
public int getBirthYear() {
return birthYear;
}
public void setBirthYear(int birthYear) {
this.birthYear = birthYear;
}
public int getBillBalance() {
return billBalance;
}
public void setBillBalance(int billBalance) {
this.billBalance = billBalance;
}
public String getSpecies() {
return Species;
}
public void setSpecies(String Species) {
this.Species = Species;
}
public String getFeature() {
return feature;
}
public void setFeature(String feature) {
this.feature = feature;
}
#Override
public String toString() {
String string = String.format("%-10s %-8d %-8d %-10s %-15s",
OwnerName, birthYear, getBalance(), Species, feature);
return string;
}
}

Initialize an object on the arraylist.get.set method?

I'm new at this.
I have something like this:
{
libri.get(i).setUtenteAssegnato(**Utente**); How do i create an Utente instance with user inputs?
}
Utente class:
package Biblioteca;
public class Utente
{
private String nome;
private String cognome;
public Utente (String unNome, String unCognome)
{
this.nome=unNome;
this.cognome=unCognome;
}
public String getNome()
{
return nome;
}
public String getCognome()
{
return cognome;
}
public String toString()
{
return (this.nome + this.cognome);
}
}
This is the Libro class, with setUtenteAssegnato method:
package Biblioteca;
public class Libro
{
private int codice;
private String titolo;
private Utente utenteAssegnato;
public Libro (int unCodice, String unTitolo)
{
this.codice = unCodice;
this.titolo = unTitolo;
this.utenteAssegnato = null;
}
public Utente getUtenteAssegnato()
{
return this.utenteAssegnato;
}
public void setUtenteAssegnato(Utente utenteAssegnato)
{
this.utenteAssegnato = utenteAssegnato;
}
public int getCodice()
{
return codice;
}
public String getTitolo()
{
return titolo;
}
public String toString()
{
return (this.codice + this.titolo + this.utenteAssegnato);
}
}
This is the class i'm having problem with:
package Biblioteca;
import java.util.ArrayList;
import java.util.List;
public class Biblioteca
{
List<Libro> libri = new ArrayList<Libro>();
List<Utente> utenti = new ArrayList<Utente>();
public Biblioteca ()
{
}
public void aggiungiUtente (String unNome, String unCognome)
{
Utente u1 = new Utente (unNome, unCognome);
utenti.add(u1);
}
public void aggiungiLibro(int unCodice, String unTitolo)
{
Libro l1 = new Libro (unCodice, unTitolo);
libri.add(l1);
}
public void creaPrestito (int unCodice, String unCognome)
{
boolean codiceTrovato = false;
boolean cognomeTrovato = false;
int i;
int j;
for (i=0; i<libri.size(); i++)
{
if (libri.get(i).getCodice() == (unCodice))
{
System.out.println("Codice trovato. ");
codiceTrovato = true;
}
else
{
System.out.println("Codice non trovato. ");
}
}
for (j=0; j<utenti.size(); j++)
{
if (utenti.get(j).getCognome().equals(unCognome))
{
System.out.println("Utente trovato. ");
cognomeTrovato = true;
}
else
{
System.out.println("Utente non trovato. ");
}
}
if (codiceTrovato && cognomeTrovato)
{
**libri.get(i).setUtenteAssegnato(Utente);**
}
}
public String toString()
{
String stampa = ", ";
for(Libro d : libri)
{
stampa += d.toString();
}
return stampa;
}
}
Basically, i don't know how to set the object in the arraylist (i) position from input (it should be 2 strings, right?)
Do i have to create another instance of Utente?

How to name a component with a string

I have a problem with that i can't get my string to be named with a string! here is my code.
public class Load {
int num = 0;
public String getstuff(){
num++;
String snum = new String("" + num);
return snum;
}
String name = this.getstuff();
public void AddString(String f, int v){
String name = this.name;
String name = new String(f + v);
}
public Load(String s){
}
}
Avoid using String constructor.
public class Load {
int num = 0;
public String getstuff() {
num++;
return "" + num;
}
String name = this.getstuff();
public void AddString(String f, int v){
this.name = this.name + f + v;
// Or
// this.name = f + v;
// Whichever behavior you want.
}
public Load(String s){
}
}
Hope this helps.
Good luck.

Java Beans to test a class

I was given a class DrivingTestM.java to test with a 2 classes I wrote. Here are the classes I wrote. When i run the DrivingTestM.java it gives me an error with the line:
System.out.println( question.getDescription() );
Im not sure what the error may be. Can anyone try and shed some light on this error? Thanks!
Question.java:
public class Question {
String description;
String answerA;
String answerB;
String answerC;
int correctAnswer;
int answer;
Boolean answerCorrect;
public Question(){
}
public Question(String description, String answerA, String answerB, String answerC, int correctAnswer, int answer){
this.description = description;
this.answerA = answerA;
this.answerB = answerB;
this.answerC = answerC;
this.correctAnswer = correctAnswer;
this.answer = answer;
}
public Question(String description, String answerA, String answerB, String answerC, int correctAnswer){
this.description = description;
this.answerA = answerA;
this.answerB = answerB;
this.answerC = answerC;
this.correctAnswer = correctAnswer;
}
public Boolean isAnswerCorrect() {
return answerCorrect;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getAnswerA() {
return answerA;
}
public void setAnswerA(String answerA) {
this.answerA = answerA;
}
public String getAnswerB() {
return answerB;
}
public void setAnswerB(String answerB) {
this.answerB = answerB;
}
public String getAnswerC() {
return answerC;
}
public void setAnswerC(String answerC) {
this.answerC = answerC;
}
public int getCorrectAnswer() {
return correctAnswer;
}
public void setCorrectAnswer(int correctAnswer) {
this.correctAnswer = correctAnswer;
}
public int getAnswer() {
return answer;
}
public void setAnswer(int answer) {
this.answer = answer;
}
}
DrivingTest.java:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class DrivingTest {
int currentQuestionIndex = 0;
Question currentQuestion;
Boolean lastQuestion;
int score;
List<Question> q = new ArrayList<Question>();
Question quest = new Question();
public DrivingTest() throws FileNotFoundException{
File f = new File("DrivingTest.txt");
//int n = 1;
Scanner sc = new Scanner(f);
while(sc.hasNextLine()){
String desc = sc.nextLine();
String A = sc.nextLine();
String B = sc.nextLine();
String C = sc.nextLine();
String h = sc.nextLine();
int a = Integer.parseInt(h);
String blank = sc.nextLine();
q.add(new Question(desc, A,B,C,a) );
}
sc.close();
}
public void setCurrentQuestionIndex(int currentQuestionIndex) {
this.currentQuestionIndex = currentQuestionIndex;
}
public int getCurrentQuestionIndex() {
return currentQuestionIndex;
}
public Boolean isLastQuestion() {
if(currentQuestionIndex == q.size() - 1){
return true;
}
else{
return false;
}
}
public Question getCurrentQuestion() {
return currentQuestion;
}
public void setCurrentQuestion(Question currentQuestion) {
this.currentQuestion = currentQuestion;
}
public int getScore() {
return score;
}
}
DrivingTestM.java (the test file):
import java.io.FileNotFoundException;
public class DrivingTestMain {
public static void main( String args[] ) throws FileNotFoundException
{
DrivingTest drivingTest = new DrivingTest();
while( true )
{
// display the current question
Question question = drivingTest.getCurrentQuestion();
System.out.println( question.getDescription() );
System.out.println( "\t" + question.getAnswerA() );
System.out.println( "\t" + question.getAnswerB() );
System.out.println( "\t" + question.getAnswerC() + "\n" );
// set the answer to the current question to 1
drivingTest.getCurrentQuestion().setAnswer( 1 );
// if this is the last question, we are done.
if( drivingTest.isLastQuestion() ) break;
// it is not the last question, so increment CurrentQuestionIndex
int currentQuestionIndex = drivingTest.getCurrentQuestionIndex();
drivingTest.setCurrentQuestionIndex( currentQuestionIndex + 1 );
}
// display the test score
System.out.println( "Your test score is: " + drivingTest.getScore() );
}
}
you're not setting the current question anywhere before you are trying to use it.
you need a method like:
public void startTest()
{
currentQuestion = q.get(0);
}
and then:
DrivingTest drivingTest = new DrivingTest();
drivingTest.startTest();
while( true )
{
//....
also ensure you have questions to get, or you will get other errors as well..
if you are using eclipse, try Debugging your code by stepping through it...
you might want to look in a better way to terminate that loop as well, currently it will fail at the end of the test...
EDIT: ok the loop wont break, but its really messy...
Edit of the DrivingTest constructor:
public DrivingTest() throws FileNotFoundException{
File f = new File("DrivingTest.txt");
//int n = 1;
Scanner sc = new Scanner(f);
while(sc.hasNextLine()){
String desc = sc.nextLine();
String A = sc.nextLine();
String B = sc.nextLine();
String C = sc.nextLine();
String h = sc.nextLine();
int a = Integer.parseInt(h);
String blank = sc.nextLine();
q.add(new Question(desc, A,B,C,a) );
}
sc.close();
//ensure it's 0.
currentQuestionIndex = 0;
//sets up your first question object.
setCurrentQuestion( q.get(currentQuestionIndex) );
}
You will get java.lang.NullPointerException because you store your Question object in Q list but you don't read objects from it. Try something like this in main class instead of:
Question question = drivingTest.getCurrentQuestion();
use
List<Question> qList = drivingTest.getQ();
Question question = qList.get(i);
also add Q getter in your DrivingTest class.
If you don't want modify main class than make changes in getCurrentQuestion() method:
int i = 0;
public Question getCurrentQuestion() {
if (i<q.size()-1)
return q.get(i++);
else return q.get(i);
}
.

Categories