I have a problem getting the variables to pass to another class, because it keeps passing me a blank variable.
I want to get the value of id from the method search() and transfer it to class foo inside the method total...
Class Boo :
//method inside of class boo
public void search(){
try{
String id = searchBox.getText();
String idNum="";
rs = stat.executeQuery("Select * from students where idNum='"+id+"'");
while(rs.next()){
idNum = rs.getString("idNum");
}//while
Members members = new Members();
setVisible(false);
members.setIdVal(id);
}catch(Exception e){
System.out.println("Error: "+e);
}
}//search
Class Foo:
// methods inside Foo
public void total(){
System.out.println("Get: "+getIdVal());
try{
rs2 = stat2.executeQuery("SELECT * FROM paymentRecord where idNum ='"+getIdVal()+"';");
}catch(Exception e){
System.out.println("Total Error: "+e);
}//
}//total
public void setIdVal(String val){
this.val = val;
}//get the id
public String getIdVal(){
//System.out.println("Inputted ID:" + val);
return this.val;
}//get the id
getIdVal() is a method of a Foo class, but it should be a method of Boo class.
class Boo {
private String id;
public void search(){
// ...
this.id = searchBox.getText();
// ...
}
public int getIdVal() {
return this.id
}
}
While the Foo class:
Class Foo {
public string Total(){
Boo boo = new Boo();
System.out.println(boo.getIdVal()); // will print the value from id searched in search() method
}
}
You have to choose where to call search() method.
Related
Firstly, I am trying to assign the value for array I initialized locally. The class type of the array is stored inside another class and the variable is private so I am using getter and setter to set the value. But it showing "Exception in thread "main" java.lang.NullPointerException at room.Test.main(Test.java:26)", below is my code for the test.java:
public class Test {
public static void main(String[] args) {
Room[] room = new Room[72];
Integer i = 0;
try {
File RoomTxt = new File("Room.txt");
Scanner read = new Scanner(RoomTxt);
while (read.hasNextLine()) {
room[i].setRoomID(read.next());
room[i].setRoomType(read.next() + " " + read.next());
room[i].setFloor(read.nextInt());
room[i].setRoomStatus(read.nextInt());
read.nextLine();
i++;
}
read.close();
} catch (FileNotFoundException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
Below is the class I used to store the Room type:
public class Room {
private String roomID;
private String roomType;
private Integer floor;
private Integer roomStatus;
//Setter
public void setRoomID(String roomID) {
this.roomID = roomID;
}
public void setRoomType(String roomType) {
this.roomType = roomType;
}
public void setFloor(Integer floor) {
this.floor = floor;
}
public void setRoomStatus(Integer roomStatus) {
this.roomStatus = roomStatus;
}
//Getter
public String getRoomID() {
return this.roomID;
}
public String getRoomType() {
return this.roomType;
}
public Integer getFloor() {
return this.floor;
}
public Integer getRoomStatus() {
return this.roomStatus;
}
}
PS. The records stored inside my Room.txt is like
RS11 Single Room 1 1
RD12 Double Room 1 0
You need to write room[I] = new Room(); before you start calling its setters.
Initializing an array only assigns the array reference to a new array object of the given type and allocates the array memory space.
Array elements reference is initialized to default element type values i.e.:
null for Object and String types
0 for numeric values
false for boolean ones
Hence all the room[i] elements refers to null.
You should be assigning element values before calling any method over these (including setters):
public class Test {
public static void main(String[] args) {
Room[] room = new Room[72];
Integer i = 0;
try {
File RoomTxt = new File("Room.txt");
Scanner read = new Scanner(RoomTxt);
while (read.hasNextLine()) {
room[I] = new Room();
// set the field values
}
read.close();
} catch (FileNotFoundException e) {
// ...
}
}
I need to use a class, which has an ArrayList of a LibraryItem type. I need to store the field values of the superclass LibraryItem and of its subclasses Book and Periodical in this ArrayList (the program reads a data file and stores each word in the approrpriate field accordingly). How can I do that?
Class - Library (class with ArrayList of LibraryItem)
public class Library
{
private ArrayList<LibraryItem> itemList; // it declares an ArrayList of LibraryItem type
public Library()
{
itemList = new ArrayList<>(); // it initalises the ArrayList of LibraryItem type
}
public void storeItem(LibraryItem libraryItem)
{
itemList.add(libraryItem);
}
// other codes omitted
if (typeOfData.equals("Book"))
{
System.out.println(lineOfText);
Scanner scanner2 = new Scanner(lineOfText);
LibraryItem libraryItem = new Book();
scanner2.useDelimiter("[,\n]");
libraryItem.readData(scanner2);
storeItem(libraryItem);
scanner2.close(); // ends scanner2
}
else if (typeOfData.equals("Periodical"))
{
System.out.println(lineOfText);
Scanner scanner2 = new Scanner(lineOfText);
LibraryItem libraryItem = new Periodical();
scanner2.useDelimiter("[,\n]");
libraryItem.readData(scanner2);
storeItem(libraryItem);
scanner2.close(); // ends scanner2
}
// other codes omitted
}
Class - LibraryItem (superclass)
public class LibraryItem
{
// fields omitted
public LibraryItem()
{
}
/**
* Mutator method used to read and store each data in the appropriate field
* #param <code>scanner2</code> Scanner is used to pass a Scanner object
* containg matching values with the field datatypes
*/
public void readData(Scanner scanner2)
{
scanner2.useDelimiter("\\s?,\\s?");
noOfPages = scanner2.nextInt();
publisher = scanner2.next();
title = scanner2.next();
itemCode = scanner2.next();
cost = scanner2.nextInt();
timesBorrowed = scanner2.nextInt();
onLoan = scanner2.nextBoolean();
}
// other codes omitted
}
Class - Book (subclass)
public class Book extends LibraryItem
{
private String author;
private String isbn;
public Book(String author, String isbn, int noOfPages, String publisher)
{
super();
this.author = author;
this.isbn = isbn;
}
public Book()
{
}
#Override
public void readData(Scanner scanner2)
{
scanner2.useDelimiter("[,\n]");
author = scanner2.next();
isbn = scanner2.next().trim();
super.readData(scanner2);
}
// other codes omitted
}
Class - Periodical (subclass)
public class Periodical extends LibraryItem
{
private String publicationDate;
public Periodical(String publicationDate)
{
super();
this.publicationDate = publicationDate;
}
public Periodical()
{
}
#Override
public void readData(Scanner scanner2)
{
scanner2.useDelimiter("[,\n]");
publicationDate = scanner2.next();
super.readData(scanner2);
}
The solution was that this code did not have any issue calling the subclasses' fields along with the subclasses. I needed to create an overridden method in the subclasses Book and Periodical:
Class - Library
LibraryItem is a polymorphic variable
public void printAllItems()
{
for (LibraryItem call : itemList)
{
call.printDetails(); // it will call the overridden method of each subclass
}
}
Abstract Class - LibraryItem
public void printDetails() // main method called by overridden methods
{
String notOnLoan = "";
if (onLoan == false)
notOnLoan = "not on";
else
notOnLoan = "on";
// these fields are used from both Book class and Periodical class
System.out.println(noOfPages + publisher);
System.out.println(title + itemCode + timesBorrowed);
System.out.println(notOnLoan + cost);
System.out.println();
}
Subclass - Book (inherits from LibraryItem)
#Override
public void printDetails()
{
System.out.println(author + isbn);
super.printDetails(); // it will run the method of subclass
}
Subclass - Periodical (inherits from LibraryItem)
#Override
public void printDetails()
{
System.out.println(publicationDate);
super.printDetails(); // it will run the method of subclass
}
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;
}
}
I've got a problem with my programm. When i try to compile following i just receive the message:
Tutorium.java:15: error: <identifier> expected
public void settName(vorlesung.lectureName) {
^
So my Code:
Tutorium.java
public class Tutorium {
private Vorlesung vorlesung;
public String tName;
private int tNumber;
public int gettNumber() {
return this.tNumber;
}
public String gettName() {
return this.tName;
}
public void settName(vorlesung.lectureName) {
this.tName = vorlesung.lectureName;
}
public String toString() {
return (this.tName + ", " + this.tNumber);
}
public Tutorium(int tNumber){
this.tNumber = tNumber; } }
Vorlesung.java
public class Vorlesung {
public String lectureName;
private int lectureNumber;
private int lecture;
private Dozent dozent;
private String lecturerlName;
public String getlectureName(){
return this.lectureName;
}
public int lectureNumber(){
return this.lectureNumber;
}
public int lecture(){
return this.lecture;
}
public String getlecturer(){
this.lecturerlName = dozent.lecturerlName;
return this.lecturerlName;
}
public String toString() {
return (this.lectureName + ", " + this.lectureNumber);
}
public Vorlesung(String lectureName, int lecture) {
this.lectureName = lectureName;
this.lecture = lecture +1;
this.lectureNumber = this.lecture -1;
this.lecturerlName = lecturerlName;
}}
My Main-Method:
public class MainVorlesung {
public static void main(String[] args) {
Student student = new Student("STUDENTNAME", "STUDENTLASTNAME", 178, 1);
Vorlesung vorlesung = new Vorlesung("Programmieren", 13341);
Tutorium tutorium = new Tutorium(3);
Dozent dozent = new Dozent("LECTURERFIRSTNAME", "LECTURERLASTNAME", 815);
System.out.println(student.toString());
System.out.println(vorlesung.toString());
System.out.println(tutorium.toString());
System.out.println(dozent.toString());
}}
My goal is to set the value of tName equal the value of vorlesung.lectureName.
Why can't i do this that way?
I appreciate every help. :)
Thanks
For methods, the arguments that you pass in must have a declared value.
In this case, a String. So you need to change your method to this:
public void settName(String newLectureName) {
this.tName = newLectureName;
}
Read more about what a java method is and how to create one here: http://www.tutorialspoint.com/java/java_methods.htm
Change settName to
public void settName(String name) {
this.tName = name;
}
Since your goal is:
My goal is to set the value of tName equal the value of vorlesung.lectureName.
You should get rid of the setName method entirely since it will depend entirely on the vorlesung field and so should not be changeable. You should also get rid of the tName field, and instead change getName() to:
public class Tutorium {
private Vorlesung vorlesung;
// public String tName; // get rid of
private int tNumber;
public String gettName() {
if (vorlesung != null) {
return vorlesung.getlecturer();
}
return null; // or throw exception
}
// *** get rid of this since you won't be setting names
// public void settName(Vorlesung vorlesung) {
// this.tName = vorlesung.lectureName;
// }
I have just now noticed that your Tutorium class does not have and absolutely needs a setVorlesung(...) method.
public void setVorlesung(Vorlesung vorlesung) {
this.vorlesung = vorlesung;
}
I have a class called 'Items' to which 'Equips' extends from and 'Helmet' then extends from 'Equips'. I have a method called 'getStats' that loads the item's stats from a .txt file. If I put the 'getStats' method in the 'Items' class, whatever field I try to access in a 'Helmet' object using 'this.' shows up null. The field I'm trying to access in 'Helmet' is initialized when the helmet is created before the text file is loaded. I could very easily just put the 'getStats' method in the 'Equips' class and put a blank 'getStats' method in the 'Items' class, but I was wondering if there was a way to make it work how it is. Thanks in advance!
Items.java:
package com.projects.aoa;
import static com.projects.aoa.Print.*;
import java.util.*;
import java.io.*;
class Items {
String name, type;
int id;
int hp, mp, str, def;
boolean vacent;
static void getAllStats(Items[] e){
for(Items i : e){
getItemStats(i);
}
}
static void getItemStats(Items i){
i.getStats();
}
void getStats(){
try {
//System.out.println(System.getProperty("user.dir"));
print(this.name); //THIS shows up as null as well as those \/below\/
FileInputStream fstream = new FileInputStream(System.getProperty("user.dir")
+ "/src/com/projects/aoa/" + this.type + this.name + ".txt");
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String line;
int counter = 0;
while ((line = br.readLine()) != null) {
if (line.length() == 0){
break;
}
switch (counter) {
case 0:
this.hp = Integer.parseInt(line);
counter++;
break;
case 1:
this.mp = Integer.parseInt(line);
counter++;
break;
case 2:
this.def = Integer.parseInt(line);
counter++;
break;
case 3:
this.str = Integer.parseInt(line);
counter++;
break;
}
}
in.close();
} catch (Exception e) {
e.printStackTrace();
}
}
Game.java:
Helmet headBand = new Helmet("HeadBand");
Helmet bronzeHelmet = new Helmet("BronzeHelmet");
Items[] equips = {
headBand, bronzeHelmet
};
getAllStats(equips);
Equips.java:
package com.projects.aoa;
import static com.projects.aoa.Print.print;
import static com.projects.aoa.Print.println;
import java.io.*;
class Equips extends Items{
String name, type;
int hp, mp, str, def;
void printStats(){
println("[" + name + "]");
println("Type: " + type);
println("HP: " + hp);
println("MP: " + mp);
println("Def: " + def);
println("Str: " + str);
}
}
class Helmet extends Equips {
Helmet(String name){
this.name = name;
this.type = "h_";
}
}
You haven't shown us your Helmet class, so it's hard to say what's going on - but my guess is that you're redeclaring fields with the same name in Helmet. Those will hide the fields in Items, whereas you really just want to use the fields from Items.
So here's a short but complete example which demonstrates what I think is going on:
class SuperClass {
String name;
public void setName(String newName) {
// This writes to the field in SuperClass
name = newName;
}
}
class SubClass extends SuperClass {
// This *hides* the field in SuperClass
String name;
public void showName() {
// This reads the field from SubClass, which
// nothing writes to...
System.out.println("My name is " + name);
}
}
public class Test {
public static void main(String[] args) {
SubClass x = new SubClass();
x.setName("Test");
x.showName();
}
}
I would recommend that:
You make all fields private, writing properties to give access to other classes as required
You get rid of the fields in Helmet which hide the ones in Items
You change your class names to avoid the plurality - Item and Equipment instead of Items
Here's a fixed version of the above code:
class SuperClass {
private String name;
public void setName(String newName) {
name = newName;
}
public String getName() {
return name;
}
}
class SubClass extends SuperClass {
public void showName() {
System.out.println("My name is " + getName());
}
}
public class Test {
public static void main(String[] args) {
SubClass x = new SubClass();
x.setName("Test");
x.showName();
}
}
(Obviously you also need to think about what access to put on the properties etc, but that's a separate matter.)