Storing input from TextFields and ComboBox in JavaFX? - java

I'm making a basic Movie Rental simulator application, and I am currently having a problem storing the input from my TextFields and my ComboBox into variables. I managed to convert most of my variables to Strings, however when I try and print the output to test it, it always returns "null."
I need to essentially figure out how to GET the selection the user has made in the combo box and store it as a string, and I need to figure out how to properly store the results from my methods. I have never ran into this problem before, so I am not really sure how to tackle it. My code is as follows:
public class RentGameDialogController extends RentalStoreGUIController implements Initializable{
/** TextField Objects **/
#FXML private TextField nameField, rentedOnField, dueBackField;
/** String for NameField **/
String name, rentedOn, dueBack;
/** Game ComboBox ID's **/
#FXML private ObservableList<GameType> cbGameOptions;
#FXML private ComboBox<GameType> cbGame;
/** Console ComboBox ID's **/
#FXML private ObservableList<PlayerType> cbConsoleOptions;
#FXML private ComboBox<PlayerType> cbConsole;
/** GameType object **/
private GameType game;
/** PlayerType Object **/
private PlayerType console;
/** Button ID's **/
#FXML Button cancel, addToCart;
/** Counter for calculating total **/
int gameCounter;
/** Stage for closing GUI **/
private Stage currentStage;
#Override
public void initialize(URL location, ResourceBundle resources) {
/** Select Console **/
cbConsoleOptions = FXCollections.observableArrayList();
for (PlayerType p : PlayerType.values()) { cbConsoleOptions.addAll(p); }
cbConsole.getItems().addAll(cbConsoleOptions);
/** Select Game **/
cbGameOptions = FXCollections.observableArrayList();
for (GameType g : GameType.values()){ cbGameOptions.addAll(g); }
cbGame.getItems().addAll(cbGameOptions);
}
public String getName(){
name = nameField.getText();
try {
String[] firstLast = name.split(" ");
String firstName = firstLast[0];
String lastName = firstLast[1];
} catch (Exception e){
e.printStackTrace();
}
return name;
}
public void getGame() {
GameType gameChoice = cbGame.getSelectionModel().getSelectedItem();
}
public void getConsole() {
PlayerType player = cbConsole.getSelectionModel().getSelectedItem();
}
public String getRentedOn() throws ParseException {
rentedOn = rentedOnField.getText();
DateFormat format = new SimpleDateFormat("dd/MM/yyyy");
Date rentedOnDate = format.parse(rentedOn);
Calendar cal = Calendar.getInstance();
cal.setLenient(false);
cal.setTime(rentedOnDate);
try {
cal.getTime();
} catch (Exception e) {
System.exit(0);
}
return rentedOn;
}
public String getDueBack() throws ParseException {
dueBack = dueBackField.getText();
DateFormat format = new SimpleDateFormat("dd/MM/yyyy");
Date dueBackDate = format.parse(dueBack);
Calendar cal = Calendar.getInstance();
cal.setLenient(false);
cal.setTime(dueBackDate);
try {
cal.getTime();
} catch (Exception e) {
System.exit(0);
}
return dueBack;
}
/*************************************
* This is the method to call the other
* String methods so their output can be
* put into my main GUI
*
* Current problem: game.toString() and console.toString() throw an InvocationTargetException
* #return
* #throws ParseException
*************************************/
public String storePurchaseData() throws ParseException {
gameCounter++; //Problem //Problem
String toList = getName() + " " + game.toString() + " " + console.toString() + " " +
getRentedOn() + " " + getDueBack();
return toList; //Returns "null null null"
}
#FXML
public void handleCancelButtonAction (ActionEvent event) {
currentStage = (Stage) cancel.getScene().getWindow();
currentStage.close();
}
#FXML
public void addToCartButton (ActionEvent event) throws ParseException {
System.out.println(storePurchaseData());
currentStage = (Stage) cancel.getScene().getWindow();
currentStage.close();
}}
Enum Classes for GameType and PlayerType(Console selection):
public enum PlayerType {
Xbox360("Xbox 360"),
PS4("Playstation 4"),
XBoxOne("Xbox One"),
WiiU("Wii - U"),
PS3("Playstation 3"),
Wii("Nintendo Wii");
private String console;
PlayerType(String console) { this.console = console; }
public String PlayerType() { return console; }
#Override public String toString() { return console; }}
GameType:
public enum GameType {
THE_WITCHER("The Witcher 3"),
CALL_OF_DUTY_AW("Call of Duty: Advanced Warfare"),
CALL_DUTY_BLOP3("Call of Duty: Black Ops 3"),
CALL_OF_DUTY_IW("Call of Duty: Infinite Warfare"),
THE_ELDER_SCROLLS("The Elder Scrolls IV: Skyrim");
private String game;
GameType(String game) {
this.game = game;
}
public String GameType() { return game; }
#Override public String toString() { return game; }}

The only method that will return the selected value is getName()
The rest of the methods you are using don't return anything
public void getGame() //Void return type
{
GameType gameChoice = cbGame.getSelectionModel().getSelectedItem();
}
All this does is create a GameType object that is accessible only inside of that method.
Instead it should be
public GameType getGame() //Instead of void, the type you are trying to get
{
return cbGame.getSelectionModel().getSelectedItem();
}
That way, you can then access the result by
GameType selectedGame = getGame();
If you want it as a String use
public String getGame()
{
return cbGame.getSelectionModel().getSelectedItem().toString();
}

Related

Reading in a .txt into ArrayList from another class [duplicate]

This question already has answers here:
Passing Parameters JavaFX FXML
(10 answers)
Closed 4 years ago.
Reading in instructions.txt from instructions.java from a comma(,) delimited method for InstructionsController so that I may present it into a TextArea on Instructions.xml.
Having trouble figuring out once I've read in the file, how to pass over the ArrayList to another class to successfully use that data.
Using about in handle as a test button in the InstructionsController class.
Instructions.java
public class Instructions {
private String[] identifier;
private ArrayList<String> listName;
private ArrayList<String> listDesc;
public void dataLoader() {
String fileName = "instructions.txt";
Scanner scan;
/*
* Shows working path System.out.println(newFile(".").getAbsoluteFile());
*/
try {
scan = new Scanner(new File(fileName));
// Iteration rather than iterable
while (scan.hasNext()) {
int i = 0;
String line = scan.nextLine();
identifier = line.split(">");
if(identifier[i].equals("TITLE")) {
listName.add(identifier[i+1]);
} else if (identifier[i].equals("DESC")) {
listDesc.add(identifier[i+1]);
} else if (identifier[i].equals("END")) {
i++;
}
}
scan.close();
} catch (FileNotFoundException exception) {
System.err.println("Failed to open instructions");
System.exit(1);
}catch (Exception e) {
e.printStackTrace();
}
}
public ArrayList<String> getListName() {
return listName;
}
public void setListName(ArrayList<String> listName) {
this.listName = listName;
}
public ArrayList<String> getListDesc() {
return listDesc;
}
public void setListDesc(ArrayList<String> listDesc) {
this.listDesc = listDesc;
}
}
InstructionsController.java
public class InstructionsController implements EventHandler<ActionEvent>, Initializable {
#FXML
private Button about, constants, professionPerks, teamCilantro, mainMenu, exit;
#FXML
private AnchorPane background;
#FXML
private TextArea text;
Main main = new Main();
private List<String> name;
private List<String> desc;
#Override
public void initialize(URL location, ResourceBundle resources) {
Instructions instructions = new Instructions();
name = instructions.getListName();
desc = instructions.getListDesc();
}
#FXML
public void handle(ActionEvent event) {
Button selected = (Button) event.getSource();
Stage stage = (Stage) selected.getScene().getWindow();
if (selected == about)
if(selected == mainMenu)
main.switchScene("fxml/Title.fxml", stage);
if(selected == exit)
stage.close();
}
}
sample text
file input: instructions.txt
TITLE> Profession Perks:
DESC> Investor: Starts with $150 bonus "Starting Cash" for a total of $650 "Starting Cash".
Farmer: Starts with 250 "Pounds of Food" and has a perk to consume food for the party at a 75% rate compared to normal.
Handyman: Significantly less likelyhood of "Wagon" breaking down.
END>
You can attempt to create an instance of the first class in the second class file. Or you can attempt to set your 'get' methods to static. Take a look at this previous SO answer.
You need to create an instance of Class A and then access the values from Class B, for example:
public class ClassA {
private int someInt;
public ClassA() {
someInt = 5;
}
public int getSomeInt() {
return someInt;
}
}
public class ClassB {
public void someMethod() {
ClassA instanceOfClassA = new ClassA();
int someIntFromClassA = instanceOfClassA.getSomeInt(); //This is now 5;
// Rest of your code here
}
}
Alternatively you can create it as a static method in ClassA and then call it in ClassB by using ClassA.getSomeInt();
Passing an array from class A to class B

Listeners and instance variable scope [javafx]

I cannot understand why I can't get proper values of my object inside a listener. I created an instance variable "plant" which is type of "Plant". Then in one of my methods I created a Plant object and assigned it to "plant variable". Then I set some fields of plant object like "name" and "id". Everything works fine but... I created a listener to open a new window after button click. And what is strange for me, inside this listener the program cannot see the plant object fields which I set earlier.
Here is my code:
class Plant {
private plantName;
private gridId;
public String getName() {
return plantName;
}
public void setName(String plantName) {
this.plantName = plantName;
}
public int gridId() {
return gridId;
}
public void setGridId(int gridId) {
this.gridId = gridId;
}
}
The following code presents fragment of GrowboxModel class where the fields for Plant object are setted:
public Plant selectAll(int gridId) throws SQLException {
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
String query = "SELECT * FROM plant WHERE gridId = ?";
Plant plant = new Plant();
try {
preparedStatement = connection.prepareStatement(query);
preparedStatement.setInt(1, gridId);
resultSet = preparedStatement.executeQuery();
while(resultSet.next()) {
plant.setName(resultSet.getString("name"));
plant.setGridId(resultSet.getInt("gridId"));
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
preparedStatement.close();
resultSet.close();
}
return plant;
}
Below is fragment of my growboxController class:
public Plant plant;
public GrowboxModel model = new GrowboxModel();
private void growboxCellContent(VBox plantAreaVbox) {
plant = model.selectAll(Integer.parseInt(plantAreaVbox.getId()));
if (plant.getName() == null) {
plantName.setText("EMPTY " + plantAreaVbox.getId());
} else {
System.out.println("FULL" + plant.getGridId());
}
}
For now everything was great. The program the fields of plant object. But the problem is below:
public void growboxCellBehaviour(VBox plantAreaVbox) {
plantAreaVbox.setOnMouseClicked(new EventHandler<MouseEvent>() {
public void handle(MouseEvent me) {
System.out.println("NAME: " + plant.getName() + ", gridId: " + plant.getGridId());
}
});
}
It was a moment when "plant.getName()" etc. are null, although should have same name.
I know how to create a workaround but just wonder if anyone know why listener can't see these fields.
In the plant class, nothing is actually being assigned you need to actually set the variables.
class Plant {
String plantName;
int id;
public String getName() {
return plantName;
}
public void setName(String plantName1) {
plantName = plantName1;
}
public int gridId() {
return gridId;
}
public void setId(int id1) {
id = id1;
}
}

JavaFX tableview not displaying properly [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
I have a JavaFX application with a scene with two tableviews, the first one works correctly, the second one doesn't.
The second tableview only displays the content of 2 out of the 5 columns it should, and the content on the second column, should be actually on the last column. I have used javaFX a few times before and it's the first time I see something like this, I revised my code 2 or 3 times looking for things that could be wrong or mispelled, but I haven't been able to find it.
This is what the tableview displays.
This is the code of the object class it contains.
public class Producte {
private int codi;
private String nom;
private String descripcio;
private float preu;
private int codiFabricant;
public Producte(String nom, String descripcio, float preu,
int codiFabricant) {
this.nom = nom;
this.descripcio = descripcio;
this.preu = preu;
this.codiFabricant = codiFabricant;
}
public Producte(int codi, String nom, String descripcio, float preu,
int codiFabricant) {
this.codi = codi;
this.nom = nom;
this.descripcio = descripcio;
this.preu = preu;
this.codiFabricant = codiFabricant;
}
public int getCodi() {
return codi;
}
public void setCodi(int codi) {
this.codi = codi;
}
public String getNom() {
return nom;
}
public void setNom(String nom) {
this.nom = nom;
}
public String getDescripcio() {
return descripcio;
}
public void setDescripcio(String descripcio) {
this.descripcio = descripcio;
}
public float getPreu() {
return preu;
}
public void setPreu(float preu) {
this.preu = preu;
}
public int getCodiFabricant() {
return codiFabricant;
}
public void setCodiFabricant(int codiFabricant) {
this.codiFabricant = codiFabricant;
}
#Override
public String toString() {
return "Producte [codi=" + codi + ", nom=" + nom + ", descripcio="
+ descripcio + ", preu=" + preu + ", codiFabricant="
+ codiFabricant + "]";
}
}
And this is the code from the method that loads the scene.
The first tableview is the dirTable, the second one(the one that doesn't work properly is the prodTable). Thanks in advance for any help :/
static Scene directorScene() {
GridPane gridPane = new GridPane();
gridPane.setAlignment(Pos.CENTER);
gridPane.setVgap(25);
gridPane.setHgap(25);
director = DirectorFunctions.director;
final ObservableList<Director> dirList = FXCollections.observableArrayList();
dirList.add(director);
TableView<Director> dirTable = new TableView<>();
dirTable.setItems(dirList);
TableColumn<Director, String> fabCol = new TableColumn<>("Fabricant");
TableColumn<Director, String> dniCol = new TableColumn<>("DNI");
TableColumn<Director, String> nomCol = new TableColumn<>("Nom");
TableColumn<Director, String> mailCol = new TableColumn<>("Mail");
TableColumn<Director, String> passCol = new TableColumn<>("Pass");
fabCol.setCellValueFactory(new PropertyValueFactory<Director,String>("Nom"));
dniCol.setCellValueFactory(new PropertyValueFactory<Director,String>("DniDirector"));
nomCol.setCellValueFactory(new PropertyValueFactory<Director,String>("NomDirector"));
mailCol.setCellValueFactory(new PropertyValueFactory<Director,String>("MailDirector"));
passCol.setCellValueFactory(new PropertyValueFactory<Director,String>("PasswordDirector"));
dirTable.getColumns().setAll(fabCol, dniCol, nomCol, mailCol, passCol);
dirTable.setMinWidth(450);
dirTable.setMaxHeight(52);
dirTable.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);
gridPane.add(dirTable, 0, 0);
Button modificarDirector = new Button("Modificar");
modificarDirector.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
// TODO Auto-generated method stub
}
});
gridPane.add(modificarDirector, 1, 0);
final ObservableList<Producte> prodList = FXCollections.observableArrayList();
for (Producte p:DirectorFunctions.productes.values()) {
prodList.add(p);
}
TableView<Producte> prodTable = new TableView<>();
prodTable.setItems(prodList);
TableColumn<Producte, String> codiPCol = new TableColumn<>("Codi");
TableColumn<Producte, String> nomPCol = new TableColumn<>("Nom");
TableColumn<Producte, String> descPCol = new TableColumn<>("DescripciĆ³");
TableColumn<Producte, String> preuPCol = new TableColumn<>("Preu");
TableColumn<Producte, String> fabPCol = new TableColumn<>("Fabricant");
codiPCol.setCellValueFactory(new PropertyValueFactory<Producte, String>("Codi"));
nomPCol.setCellValueFactory(new PropertyValueFactory<Producte, String>("Nom"));
nomPCol.setCellValueFactory(new PropertyValueFactory<Producte, String>("Descripcio"));
nomPCol.setCellValueFactory(new PropertyValueFactory<Producte, String>("Preu"));
nomPCol.setCellValueFactory(new PropertyValueFactory<Producte, String>("CodiFabricant"));
prodTable.getColumns().setAll(codiPCol, nomPCol, descPCol, preuPCol, fabPCol);
prodTable.setMinWidth(450);
prodTable.setMaxHeight(200);
prodTable.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);
gridPane.add(prodTable, 0, 1);
Button nouButton = new Button("Nou");
nouButton.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
// TODO Auto-generated method stub
}
});
nouButton.setMinWidth(75);
Button modButton = new Button("Modificar");
modButton.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
// TODO Auto-generated method stub
}
});
modButton.setMinWidth(75);
Button delButton = new Button("Borrar");
delButton.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
// TODO Auto-generated method stub
}
});
delButton.setMinWidth(75);
Button backButton = new Button("Tornar");
backButton.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
// TODO Auto-generated method stub
}
});
backButton.setMinWidth(75);
gridPane.add(backButton, 1, 2);
VBox vbox = new VBox(25);
vbox.getChildren().addAll(nouButton, modButton, delButton);
gridPane.add(vbox, 1, 1);
Scene scene = new Scene(gridPane, 640, 480, Color.web("eee"));
return scene;
}
This is the Director class for whoever wants to see it as well
public class Director {
private int codi;
private String nom;
private String dniDirector;
private String nomDirector;
private String mailDirector;
private String passwordDirector;
public Director(int codi, String nom, String dniDirector,
String nomDirector, String mailDirector, String passwordDirector) {
this.codi = codi;
this.nom = nom;
this.dniDirector = dniDirector;
this.nomDirector = nomDirector;
this.mailDirector = mailDirector;
this.passwordDirector = passwordDirector;
}
public int getCodi() {
return codi;
}
public void setCodi(int codi) {
this.codi = codi;
}
public String getNom() {
return nom;
}
public void setNom(String nom) {
this.nom = nom;
}
public String getDniDirector() {
return dniDirector;
}
public void setDniDirector(String dniDirector) {
this.dniDirector = dniDirector;
}
public String getNomDirector() {
return nomDirector;
}
public void setNomDirector(String nomDirector) {
this.nomDirector = nomDirector;
}
public String getMailDirector() {
return mailDirector;
}
public void setMailDirector(String mailDirector) {
this.mailDirector = mailDirector;
}
public String getPasswordDirector() {
return passwordDirector;
}
public void setPasswordDirector(String passwordDirector) {
this.passwordDirector = passwordDirector;
}
#Override
public String toString() {
return "Fabricant [codi=" + codi + ", nom=" + nom + ", dniDirector="
+ dniDirector + ", nomDirector=" + nomDirector
+ ", mailDirector=" + mailDirector + ", passwordDirector="
+ passwordDirector + "]";
}
}
I would advice you to use JavaFX Property for all your model. You can find samples in here.
PropertyValueFactory<S,T> looks for a property of type T in S with the same name that you typed in the constructor.
For example, in a model class Product which has a StringProperty field name,
new PropertyValueFactory<Product, String>("name")
will look for :
nameProperty()
and if it doesn't find it, it will further look for getName() and wrap it in a ReadOnlyObjectWrapper before returning it.
From the docs,
If no method matching this pattern exists, there is fall-through
support for attempting to call get() or is() (that
is, getFirstName() or isFirstName() in the example above). If a method
matching this pattern exists, the value returned from this method is
wrapped in a ReadOnlyObjectWrapper and returned to the TableCell
The problem in your example is that your table column has a cellValueFactory which says,
nomPCol.setCellValueFactory(new PropertyValueFactory<Producte, String>("Preu"));
but your getter method is returning a float instead of a String
public float getPreu() {
return preu;
}
I found the problem already, I used copy+paste to duplicate lines of the code and I forgot to change the name on the columns for the table. I'm an idiot -__-.
Sorry for wasting your time guys...
By the way, is there a way to close a thread/question without having to ask mods or something?

Update highlighted cell in javafx

I use two text fields and a button to add entries to a two column table.
If I add a new entry the table is updated right away:
private void addBtn(ActionEvent event) {
Test o = new Test();
o.setTitle(title.getText());
o.setCount(Integer.parseInt(count.getText()));
mainApp.getData().add(o);
}
In a second step I added an additional button to amend the highlighted count cell:
private void editBtn(ActionEvent event) {
Test o = getSelection();
o.setCount(Integer.parseInt(count.getText()));
mainApp.getData().set(tablePosition, o);
}
If I click the button, the cell will update the value, but it's not visible in the table. If I click the button a second time it will update the table.
To check for which row is highlighted I use the following functions:
private final ListChangeListener<Test> selector = new ListChangeListener<Test>() {
#Override
public void onChanged(ListChangeListener.Change<? extends Test> c) {
setSelection();
}
};
public Test getSelection() {
if (testTable != null) {
List<Test> table = testTable.getSelectionModel().getSelectedItems();
if (table.size() == 1) {
final Test selection = table.get(0);
return selection;
}
}
return null;
}
private void setSelection() {
final Test o = getSelection();
tablePosition = mainApp.getData().indexOf(o);
if (o != null) {
title.setText(o.getTitle());
count.setText(o.getCount().toString());
}
}
In the initialize method I add a listener to the observable list:
final ObservableList<Test> t1 = testTable.getSelectionModel().getSelectedItems();
t1.addListener(selector);
My Test class:
public class Test {
private final SimpleStringProperty title = new SimpleStringProperty();
private final SimpleIntegerProperty count = new SimpleIntegerProperty();
public void setTitle(String title) {
this.title.set(title);
}
public String getTitle() {
return title.get();
}
public void setCount(Integer count) {
this.count.set(count);
}
public Integer getCount() {
return count.get();
}
}
How can I make the Edit button to update the cell value right away?
Assuming you are using a PropertyValueFactory as the cell factory for your table columns, you need to provide property accessor methods in order that the table cell provided by the PropertyValueFactory can listen to those properties for changes.
One correct implementation of using the JavaFX Property model looks like
public class Test {
private final IntegerProperty count = new SimpleIntegerProperty(this, "count", 0);
private final StringProperty title = new SimpleStringProperty(this, "title", "");
public final int getCount() {
return count.get();
}
public final void setCount(int count) {
this.count.set(count);
}
public IntegerProperty countProperty() {
return count ;
}
public final String getTitle() {
return title.get();
}
public final void setTitle(String title) {
this.title.set(title);
}
public StringProperty titleProperty() {
return title ;
}
}
With that, the following method will then correctly update the selected row in the table:
private void editBtn(ActionEvent event) {
Test o = testTable.getSelectionModel().getSelectedItem();
if (o != null) {
o.setCount(Integer.parseInt(count.getText()));
}
}
If that doesn't fix the problem for you, I recommend you edit your question completely and provide a sscce that demonstrates the problem.

Value isn't getting stored in Array?

I have four classes. Project Class, Student Class, ProjectFile Class and ProjectFrame JFrame.
The ProjectFrame is only for GUI and i haven't touched that.
The Student and Project Class are constructors and i've coded those.
Now i'm trying to implement the ProjectFile class by reading from a text file and then storing the data to be read. I am having trouble as i'm not sure why the Instance of the Project Class isn't storing the data. I've looked at my loops and i did print the variables to be sure that the loop is actually happening. It works for the first time but when i try to call the second array, it gives me a NullPointerException. So i'm assuming it's storing the value as null but that shouldn't be the case.
This is my ProjectFile Class
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package DecelAssignment;
import java.io.*;
/**
*
* #author Zane
*/
public class ProjectFile {
private static Project[] pJect;
private static Student[] sDent;
private static Project ja;
private static BufferedReader br;
public static void readData() {
File inputFile = new File("projects.txt");
try {
br = new BufferedReader(new FileReader(inputFile));
String s = br.readLine();
pJect = null;
pJect = new Project[Integer.parseInt(s)];
//System.out.println(s);
for (int i = 0; i < pJect.length; i++) {
s = br.readLine();
if (s == null) {
break;
} else {
String sLine[] = s.split(",");
int count = 3;
// for (int i2 = 0; i2 < Integer.parseInt(sLine[3]); i2++) {
// sDent[i2] = new Student(sLine[count+1], sLine[count+2], sLine[count+3], sLine[count+4]);
// count += 4;
// }
pJect[i] = new Project(sLine[0], sLine[1], sLine[2], sDent);
System.out.println(pJect[1].getTitle());
System.out.println(sLine[0]);
System.out.println(i);
}
}
} catch (IOException e) {
System.out.println("I caught an IO Exception1");
}
// } catch (NullPointerException e) {
// e.printStackTrace();
// System.out.println("I caught a Null Pointer Exception!");
//
// }
}
// public Project[] getProjectInfo() {
//
//
// return;
// }
public static void main(String[] args) {
readData();
}
}
This is the text file i'm reading from
3
iPhone App,EEE,John Tan,1,P109520,Kelvin Tay,DBIT,M
iPad App,DMIT,Mark Goh,3,P106286,Felicia Wong,DIT,F,P101803,Rachel Chang,DIT,F,P100036,Lewis Poh,DBIT,M
Green Living,DMIT,Audrey Lim,2,P101234,Peter Chua,DIT,M,P103287,Ng Ming Shu,DISM,F
Can someone please explain to me where i'm coding this wrongly? I can't figure it out.
EDIT:
This is the Project Class
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package DecelAssignment;
/**
*
* #author Zane
*/
public class Project {
private String title, school, supervisor;
private Student[] stDent;
public Project() {
title = "";
school = "";
supervisor = "";
stDent = new Student[0];
}
public Student[] getStDent() {
return stDent;
}
public Project(String title, String school, String supervisor, Student[] stDent) {
this.title = title;
this.school = school;
this.supervisor = supervisor;
this.stDent = stDent;
}
public String getSchool() {
return school;
}
public void setSchool(String school) {
this.school = school;
}
public String getSupervisor() {
return supervisor;
}
public void setSupervisor(String supervisor) {
this.supervisor = supervisor;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
}
I guess your code crashes here
System.out.println(pJect[1].getTitle());
In the first loop pJect[1] will contain null which causes a crash
You probably intend
System.out.println(pJect[i].getTitle());

Categories

Resources