why is classNotFoundException being generated? - java

Why is my program generating this exception:
Exception in thread "main" java.lang.ClassNotFoundException:
writecoursefile.Course
when the class Course is defined in my code?
I'm not sure what the "writcoursefile" is because that isn't anywhere in my program.
This program is meant to deserialize a .ser file, sort, then print to csv file. I'm only up to the deserialization part though. The class Course was provided by my teacher.
/*
fallListSort Application
Created for CSci 112 by Steve Pesce
last Edited 3/16
*/
package falllistsort;
import java.io.*;
public class FallListSort {
public static void main(String[] args) throws Exception
{
//declare new course array
Course[] fall2014 = new Course[24];
//use fall2014.ser to define fall2014[]
fall2014 = readFromFile();
//Test: print array
for (Course course: fall2014)
{
System.out.println(course.toString());
}
}
public static Course[] readFromFile() throws Exception
{
Course[] course = null; //course object to holde file data
//declare file and object stream variables and initialize to null
FileInputStream fallFile = null;
ObjectInputStream infile = null;
try
{ //File and stream objects
fallFile = new FileInputStream("fall2014.ser");
infile = new ObjectInputStream(fallFile);
//read objects from file
course = (Course[]) infile.readObject();
} catch (IOException exc)
{
exc.printStackTrace();
}finally
{
infile.close();
}
return course;
}// end readfromFile()
public static void writeCSV(Course[] courseArray, int count) throws Exception
{
java.io.File courseCSV = new java.io.File("courses.csv");
java.io.PrintWriter outfile = new java.io.PrintWriter(courseCSV);
}
}
class Course implements Serializable {
private String campus; // the campus on which the course is offered
private String course; // the course number, such as CSCI 111
private String section; // the section number
private String crn; // the CRN for this section
private int credits; // the number od credits for the course
private String time; // the time the course is offered, such as 8:00 to 10:00 A.M.
private String days; // the Days the course is offered, suhc as MW
// constructors
Course() {
}
Course(String course, String section, String crn, int credits) {
this.course = course;
this.section = section;
this.crn = crn;
this.credits = credits;
} // end Course() initalizing
// muatator methods
public void setCampus(String cmp) {
this.campus = cmp;
}// end setCampus()
public void setCourse(String crse) {
this.course = crse;
}// end setCourse()
public void setSection(String sect) {
this.section = sect;
} // end setSection()
public void setCRN(String crn) {
this.crn = crn;
} // end setCRN()
public void setCredits(int cr) {
this.credits = cr;
} // end setCredits()
public void setTime(String tm) {
this.time = tm;
}// end setTime()
public void setDays(String days) {
this.days = days;
}// end setDays()
// accessor methods
public String getCampus() {
return campus;
} // end getCampus()
public String getCourse() {
return course;
} // end Course()
public String getSection() {
return section;
} // end getSection()
public String getCRN() {
return crn;
} // end getCRN()
public int getCredits() {
return credits;
} // end getCredits()
public String getTime() {
return time;
} // end getTime()
public String getDays() {
return days;
} // end getDays()
// method to compare by CRN using the String class compareTo()
public int compareTo(Course other) {
return this.crn.compareTo(other.getCRN());
} // end compareTO()
// method to return properties as a string
public String toString() {
return campus + " "
+ course + " "
+ section + " "
+ crn + " "
+ credits + " "
+ time + " "
+ days;
} // end toString()
// You will need to add a method to return properties as a CSV string on one line
/* public String toCSVString() {
} // end toCSVString()
*/
}// end class Course

Related

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;
}
}

How can I implement the count 60 seonds for hospital

Who can help me to implement the function if the patient waiting for over 60 seconds the category will change from "low" to "high" and queue behind the newest patient category with "high". Can someone help to me to solve it?
EmergencyRoomSimulator1.java :
package emergencyroomsimulator1;
import java.util.Random;
public class EmergencyRoomSimulator1 {
private static final int WAIT_LIMIT = 1000; // 1000 = 1 second
private PatientQueue pq = new PatientQueue();
private void t() {
try { Thread.sleep(new Random().nextInt(WAIT_LIMIT));
} catch (InterruptedException e) {
}
} // end t method
private void patientArrives(Patient p) {
pq.registerPatient(p);
System.out.println(" ARRIVAL: " + p.getID());
System.out.println(" time arrived: " + p.getTimeArrived());
System.out.println(" category: " + p.getCategory());
System.out.println("------------------------------------");
t();
} // end patientArrives method
public void doctorVisits() {
Patient p = pq.getNextPatient();
System.out.println(" VISIT: " + p.getID());
System.out.println(" time arrived: " + p.getTimeArrived());
System.out.println(" category: " + p.getCategory());
System.out.println("------------------------------------");
t();
} // end doctorVisits method
private void simulate() {
System.out.println("------------------------------------");
System.out.println("ER OPEN");
System.out.println("------------------------------------");
patientArrives(new Patient(100, "high"));
patientArrives(new Patient(101, "low"));
patientArrives(new Patient(102, "low"));
patientArrives(new Patient(103, "high"));
patientArrives(new Patient(104, "high"));
patientArrives(new Patient(105, "low"));
patientArrives(new Patient(106, "low"));
patientArrives(new Patient(107, "high"));
doctorVisits();
doctorVisits();
doctorVisits();
doctorVisits();
doctorVisits();
doctorVisits();
System.out.println("------------------------------------");
System.out.println("ER CLOSED");
System.out.println("------------------------------------");
}
public static void main(String[] args) {
// TODO code application logic here
EmergencyRoomSimulator1 er = new EmergencyRoomSimulator1();
er.simulate();
} // end main
}
Patient.java :
package emergencyroomsimulator1;
import java.util.Date;
public class Patient implements Comparable<Patient> {
protected int id;
protected String category;
protected Date timeArrived;
EmergencyRoomSimulator1 emg;
//protected Date CurrentTime;
// accessors and mutators
public int getID() {
return id;
}
public void setID(int idIn) {
this.id = idIn;
}
public String getCategory() {
return category;
}
public void setCategory(String categoryIn) {
this.category = categoryIn;
}
public java.util.Date getTimeArrived() {
return timeArrived;
}
public int compareTo(Patient other) {
// This code doesn't handle nulls
int result = getCategory().compareTo(other.getCategory());
if (result == 0) {
result = getTimeArrived().compareTo(other.getTimeArrived());
}
return result;
}
// default constructor
public Patient() {
this.id = 0;
this.category = "low"; // unclassified Patients go to the end of the queue
this.timeArrived = new Date();
}
// overloaded constructor
public Patient(int idIn, String categoryIn) {
this.id = idIn;
this.category = categoryIn;
this.timeArrived = new Date();
}
}
PatientComparator.java:
package emergencyroomsimulator1;
import java.util.Comparator;
public class PatientComparator implements Comparator<Patient>{
public int compare(Patient p1, Patient p2) {
int result = p1.getCategory().compareTo(p2.getCategory());
if (result == 0) {
result = p1.getTimeArrived().compareTo(p2.getTimeArrived());
}
return result;
}
}
PatientQueue.java :
package emergencyroomsimulator1;
import java.util.Comparator;
import java.util.PriorityQueue;
public class PatientQueue {
PriorityQueue pq;
// default constructor
public PatientQueue() {
this.pq = new PriorityQueue<Patient>(1, new PatientComparator());
}
public void registerPatient(Patient p) {
this.pq.add(p);
} // end registerPatient method
public Patient getNextPatient() {
return (Patient) this.pq.poll();
} // end getNextPatient method
}

How to input data in the very best way in object programming Java

Just to let you know:
I know how to use Scanner od BufferedReader, just dont know where to use it in this case.
I am working on my first bigger app in Java.
(I had to use SQLite as a DB)
That's some kind of gym app, where I will add my workouts (4 simple variables)
And then it will be saved in DB and sorted to read out.
My question is...
How should I add an Input from the user?
I have setters and getters and no Idea where this input should be added.
In main class? Should I build a new method?
package bazadanych;
import java.util.List;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
DBConnector d = new DBConnector();
d.addWorkout( "bicek", 12, 5,22052019);
List<Workout> workouts = d.allWorkouts();
for (int i=0; i < workouts.size(); i++) {
System.out.println("---------------------------------");
System.out.println("The name of the excersise: " + workouts.get(i).getName());
System.out.println(" Number of reps: " + workouts.get(i).getReps());
System.out.println(" Weight: " + workouts.get(i).getWeight() + "kg");
System.out.println("Date: " + workouts.get(i).getDate());
System.out.println("---------------------------------");
}
}
package bazadanych;
public class Workout extends DBConnector {
private int workoutId;
private String name;
private int reps;
private int weight;
private int date;
public Workout(int workoutId, String name, int weight, int reps, int date)
{
setWorkoutId(workoutId);
setName(name);
setWeight(weight);
setReps(reps);
setDate(date);
}
// Getters
public int getDate()
{
return date;
}
public int getWorkoutId()
{
return workoutId;
}
public String getName()
{
return name;
}
public int getReps()
{
return reps;
}
public int getWeight()
{
return weight;
}
//Setters
public void setDate(int date)
{
this.date = date;
}
public void setName(String name)
{
this.name = name;
}
public void setReps(int reps)
{
this.reps = reps;
}
public void setWorkoutId(int workoutId)
{
this.workoutId = workoutId;
}
public void setWeight(int weight)
{
this.weight = weight;
}
}
package bazadanych;
import java.sql.*;
import java.util.LinkedList;
import java.util.List;
public class DBConnector {
// connection with datebase
private Connection conn;
// The object used to execute a static SQL statement and returning the results
private Statement stat;
// Construct
public DBConnector()
{
try
{
Class.forName("org.sqlite.JDBC");
}
catch (ClassNotFoundException e)
{
System.err.println("There is no JDBC driver");
e.printStackTrace();
}
try
{
conn = DriverManager.getConnection("jdbc:sqlite:GymApp.db"); // GymApp will be the name of the datebase
stat = conn.createStatement();
}
catch (SQLException e)
{
System.err.println("I can not connect");
}
CreateStructure();
}
public boolean CreateStructure()
{
// Rule to delete the table and create new, when we want to rework number of columnes etc.
// String dropFirst = "DROP TABLE IF EXISTS workouts;";
String sql = "CREATE TABLE IF NOT EXISTS workouts"
+ "("
+ "workoutId INTEGER PRIMARY KEY AUTOINCREMENT,"
+ "name varchar(100),"
+ "reps INTEGER, "
+ " weight INTEGER,"
+ " date INTEGER"
+ ")";
try
{
// stat.execute(dropFirst);
stat.execute(sql);
}
catch (SQLException e)
{
System.err.println("There is a problem by Structure creation");
e.printStackTrace();
return false;
}
return true;
}
public boolean addWorkout( String name, int reps, int weight, int date)
{ String sql = " insert into workouts values (Null,?,?,?,?);";
try
(PreparedStatement pStmt = conn.prepareStatement(sql)){
pStmt.setString(1, name);
pStmt.setInt(2,reps);
pStmt.setInt(3,weight);
pStmt.setInt(4, date);
pStmt.execute();
}
catch(SQLException e)
{
System.err.println("Can not add a new contact");
e.printStackTrace();
return false;
}
return true;
}
public List<Workout> allWorkouts()
{
List<Workout> workouts = new LinkedList<Workout>();
try {
ResultSet show = stat.executeQuery("SELECT * FROM workouts ORDER BY date");
int id;
String name;
int reps;
int weight;
int date;
while (show.next())
{
id = show.getInt("workoutId");
name = show.getString("name");
reps = show.getInt("reps");
weight = show.getInt("weight");
date = show.getInt("date");
workouts.add(new Workout(id, name,reps,weight,date));
}
}
catch (SQLException e)
{
e.printStackTrace();
return null;
}
return workouts;
}
public void closeConnection() {
try{
conn.close();
}
catch (SQLException e) {
System.err.println("There is connection closing error");
e.printStackTrace();
}
}
}
To answer your main question, you should add the input from the user in the main method. You'd use an instance of Scanner to read the values of workout name, reps and weight. Date you could simply pick up the current date, code sample below.
A few other recommendations:
1 - Change the workout date to long, that's a standard in the industry.
2 - The method CreateStructure does not follow Java coding standards, rename it to createStructure.
3 - You are storing the workout ID as NULL, that could cause you trouble later when trying to retrieve the data from the database.
Code sample:
public static void main(String[] args) {
DBConnector d = new DBConnector();
// Retrieve input from the user
Scanner sc = new Scanner(System.in);
String name = sc.nextLine();
int reps = sc.nextInt();
int weight = sc.nextInt();
// create the workout with the data
d.addWorkout( name, reps, weight, LocalDate.now().toEpochDay());
List<Workout> workouts = d.allWorkouts();
// print workouts
}

Java static/nonstatic method

I started working on my first java project, which is a basic RPG, and I have a question regarding the spells. I have an abstract class named Character, which is extended by some subclasses (like Fighter, Mage etc.). Only spellcasters can cast spells. Regarding Spells - I have a class named Spell that describes a spell (it's name, it's effect, mana etc.). All the spells are stored in SpellsList class that has a spellsList list (objects of class Spell). I have an Effect class (very plausible that it will become an interface) that has some effects like "damage" and "heal", but I don't make use of that for the meanwhile, I just want to test that what I have works.
My problem is that Mage's methods addToSpellBook and showSpellBook give a compiler error: java can't find symbol: method addToSepllBook, location: variable hero of type Game.Character. also for showSpellBook. Why and how to fix it ?
(The problem is probably in Mage/Spell/SpellsList class, and not Character which is long, so it's less intimidating :) )
public class Game {
public static void main(String[] args) throws IOException {
CharacterCreator heroCreator = new CharacterCreator();
CharacterCreator.showAllClasses();
Scanner sc = new Scanner(System.in);
int scan = sc.nextInt();
String chosenClass = CharacterCreator.getCharacterClass(scan);
Character hero = CharacterCreator.createCharacter(chosenClass);
try {
hero.displayCharacter();
}catch (Exception e){
System.out.println("Wrong input");
}
if (hero.getCharacterClass().equals("Mage")){
hero.addToSpellBook("Fireball");
hero.showSpellBook();
}
}
}
public class CharacterCreator {
public static Character createCharacter(String chosenClass) {
Character hero = null;
System.out.println("Choose Name:");
Scanner nameIn = new Scanner(System.in);
String name = nameIn.next();
switch (chosenClass) {
case "Fighter":
return new Fighter(name);
case "Rogue":
return new Rogue(name);
case "Mage":
return new Mage(name);
case "Cleric":
return new Cleric(name);
case "def":
System.out.println("Wrong input");
return null;
default:
return null;
}
}
public static void showAllClasses(){
System.out.println("Choose a character: ");
System.out.println("1. Fighter");
System.out.println("2. Rogue");
System.out.println("3. Mage");
System.out.println("4. Cleric");
}
public static String getCharacterClass(int scan){
String classIn;
switch (scan) {
case 1:
classIn = "Fighter";
break;
case 2:
classIn = "Rogue";
break;
case 3:
classIn = "Mage";
break;
case 4:
classIn = "Cleric";
break;
default:
System.out.println("Enter again");
classIn = "def";
}
return classIn;
}
}
abstract public class Character {
private String name;
private String characterClass;
private int level;
private int hp;
private int currentHp;
private int armorClass;
private long xp;
/*private int BAB; /*Base attack bonus*/
private int strength;
private int constitution;
private int dexterity;
private int intelligence;
private int wisdom;
private int charisma;
protected Character(String name){
setName(name);
setCharacterClass("Class");
setLevel(1);
setStrength(10);
setConstitution(10);
setDexterity(10);
setIntelligence(10);
setWisdom(10);
setCharisma(10);
setHp(0);
setCurrentHp(getHp());
setArmorClass(10);
setXp(0);
}
void displayCharacter() throws IOException{
System.out.print("\n\n\n");
System.out.println("Name: " + getName());
System.out.println("Class: " + getCharacterClass());
System.out.println("Level: " + getLevel());
System.out.println("HP: " + getHp());
System.out.println("Current HP: " + getCurrentHp());
System.out.println("Armor Class: " + getArmorClass());
System.out.println("***************");
System.out.println("Attributes: ");
System.out.println("Strength: " + getStrength());
System.out.println("Constitution: " + getConstitution());
System.out.println("Dexterity: " + getDexterity());
System.out.println("Intelligence: " + getIntelligence());
System.out.println("Wisdom: " + getWisdom());
System.out.println("Charisma: " + getCharisma());
System.out.println("***************");
System.out.println("XP: " + getXp());
}
public int getModifier(int number){
int mod = (int)((number -10)/2);
return mod;
}
public String getName() { return name; }
public String getCharacterClass() { return characterClass; }
public int getLevel() { return level; }
public int getHp() { return hp; }
public int getCurrentHp() { return currentHp; }
public int getArmorClass() { return armorClass; }
public int getStrength(){ return strength; }
public int getConstitution(){ return constitution; }
public int getDexterity(){ return dexterity; }
public int getIntelligence(){ return intelligence; }
public int getWisdom(){ return wisdom; }
public int getCharisma(){ return charisma;}
public long getXp(){ return xp;}
protected void setName(String Name) { name = Name; }
protected void setCharacterClass(String characterClass) { this.characterClass = characterClass; }
protected void setLevel(int lvl){ level = lvl; }
protected void setHp(int hitPoints){ hp = hitPoints; }
protected void setCurrentHp(int curHp){ currentHp = curHp; }
protected void setArmorClass(int ac){ armorClass = ac; }
protected void setStrength(int str){ strength = str; }
protected void setConstitution(int con){ constitution = con; }
protected void setDexterity( int dex) { dexterity = dex; }
protected void setIntelligence(int intel){ intelligence = intel; }
protected void setWisdom(int wis){ wisdom = wis; }
protected void setCharisma(int cha){charisma = cha; }
protected void setXp(int XP){xp = XP; }
}
public class Mage extends Character {
private List<Spell> spellBook;
public Mage(String name){
super(name);
setName(name);
setCharacterClass("Mage");
setLevel(1);
setStrength(10);
setConstitution(10);
setDexterity(14);
setIntelligence(16);
setWisdom(14);
setCharisma(10);
setHp((int) (4 + getModifier(getConstitution())));
setCurrentHp(getHp());
setArmorClass(10 + getModifier(getDexterity()));
spellBook = null;
}
void addToSpellBook(String spellName){
Spell newSpell;
newSpell = SpellsList.getSpell(spellName);
spellBook.add(newSpell);
}
void showSpellBook(){
for (Iterator<Spell> iter = spellBook.iterator(); iter.hasNext(); ) {
Spell spell = iter.next();
if (spellBook.equals(spell.getSpellName())) {
System.out.println("Spell name: " + spell.getSpellName());
System.out.println("Spell effect: " + spell.getEffect());
}
}
}
}
public class Spell {
private String name;
private int spellLevel;
private String effect;
private int manaCost;
private int duration;
Spell(String name, int spellLevel, String effect, int manaCost, int duration){
this.name = name;
this.spellLevel = spellLevel;
this.effect = effect;
this.manaCost = manaCost;
this.duration= duration;
}
void castSpell(String spellName, Character hero, Character target){
try {
Spell spell = SpellsList.getSpell(spellName);
System.out.println("You casted: " + spellName);
System.out.println("Spell effect: " + spell.effect);
}
catch (Exception e){
System.out.println("No such spell");
}
}
String getSpellName(){ return name; }
int getSpellLevel() {return spellLevel; }
String getEffect(){ return effect; }
int getManaCost(){
return manaCost;
}
int getDuration() { return duration; }
}
public class SpellsList {
static List<Spell> spellsList = new ArrayList<Spell>();
static
{
spellsList.add(new Spell("Fireball", 3, "damage", 5,0 ));
spellsList.add(new Spell("Ice Storm", 4, "damage", 8, 0));
spellsList.add(new Spell("Heal", 2, "heal", 4, 0));
}
static Spell getSpell(String spellName) {
try {
for (Iterator<Spell> iter = spellsList.iterator(); iter.hasNext(); ) {
Spell spell = iter.next();
if (spellName.equals(spell.getSpellName())) {
return spell;
}
}
} catch (Exception e){
System.out.println(spellName + " haven't been found in spells-list");
return null;
}
return null;
}
}
hero is of type Character. You should cast it to Mage. or add addToSpellBook in Character class and override it in Mage class. Something like:
if(hero instanceof Mage)
((Mage) hero).addToSpellBook();
There is a difference between the type of variables when compiling and their class during execution. The problem is that your hero variable is not of type Mage but of type Character and only has access to methods available to any Character.
The compiler also doesn't notice your logic in attempting to make sure hero is an instance of Mage. To tell it you know you have Mage and want to use Mage methods you need to cast.
Your way of verifying is okay, but I would advise using theinstanceof keyword.
if(hero instanceof Mage) {
((Mage)hero).addToSpellBook("Fireball");
((Mage)hero).showSpellBook();
}
You call the methodes addToSpellBook and showSpellBook on the class Character, but you have no methodes with this names in your class Character.

java.lang.NullPointerException when deserializing

public class ViewBooking extends javax.swing.JFrame {
/**
* Creates new form ViewBooking
*/
public ViewBooking() {
initComponents();
}
public void dispBookingInfo(){
Reservation[] reservations = new Reservation[1];
try {
String searchCust = SearchName.getText();
FileInputStream inStream = new FileInputStream(searchCust +
"booking.dat");
ObjectInputStream objectInputFile = new ObjectInputStream(inStream);
reservations[0] = (Reservation) objectInputFile.readObject();
objectInputFile.close();
} catch (Exception e) {
}
JOptionPane.showMessageDialog(null, reservations[0].getDetails());
}
This is my Reservation class
public class Reservation implements Serializable {
private String name;
private String sDate;
private String eDate;
private String noOfDays;
private String roomNo;
private String totalAmt;
Reservation(String name, String sDate, String eDate, String noOfDays,
String totalAmt, String roomNo) {
this.name = name;
this.totalAmt = totalAmt;
this.roomNo = roomNo;
//throw new UnsupportedOperationException("Not supported yet.");
//To change body of generated methods, choose Tools | Templates.
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getsDate() {
return sDate;
}
public void setsDate(String sDate) {
this.sDate = sDate;
}
public String geteDate() {
return eDate;
}
public void seteDate(String eDate) {
this.eDate = eDate;
}
public String getNoOfDays() {
return noOfDays;
}
public void setNoOfDays(String noOfDays) {
this.noOfDays = noOfDays;
}
public String getRoomNo() {
return roomNo;
}
public void setRoomNo(String roomNo) {
this.roomNo = roomNo;
}
public String getTotalAmt() {
return totalAmt;
}
public void setTotalAmt(String totalAmt) {
this.totalAmt = totalAmt;
}
public String getDetails(){
return "Name: " + name + "\n" + "From: " + sDate + " to " + eDate
+ "\n" + "Duration: " + noOfDays + "Room No: " + roomNo
+ "Total amount: RM" + totalAmt;
}
}
I am able to serialize the Reservation object but when i try to deserialize it and read the data, i get a NullPointerException error at this line:
JOptionPane.showMessageDialog(null, reservations[0].getDetails());
What is the problem here?
I have changed my code into the following:
public void dispBookingInfo() throws Exception{
String searchCust = SearchName.getText();
FileInputStream inStream = new FileInputStream(searchCust + " booking.dat");
ObjectInputStream objectInputFile = new ObjectInputStream(inStream);
Reservation[] reservations = new Reservation[1];
try {
if (reservations[0] != null) {
reservations[0] = (Reservation) objectInputFile.readObject();
}
objectInputFile.close();
} catch (Exception e) {
System.out.println("error!");
}
JOptionPane.showMessageDialog(null, reservations[0].getDetails());
}
The NullPointerException error is gone but I still cant retrieve any data. Why is my reservation[0] null?
In your
try {
...
} catch () {
...
}
statement you ignore any exception thrown. Hence it is possible that
reservations[0] = (Reservation) objectInputFile.readObject();
does not initialize reservation[0] at all, which would cause an NullPointerException when accessing:
reservation[0].getDetails();
Here is your problem:
if (reservations[0] != null) {
reservations[0] = (Reservation) objectInputFile.readObject();
}
reservations[0] will always be null at this point because you've only just initialised the array. This stops the call that would populate the data into here, so when you try and access it later on with reservations[0].getDetails() that element is inevitably still null. The null check is completely unneeded, so remove it.
You may also wish to consider defining a serialVersionUID for your class.
To do so, add this as a class variable:
private static final long serialVersionUID = <some_long_number>;
Replace <some_long_number> with any long that you like. Once done, you'll have to re-create your file with a 'new' version of your class, otherwise the version numbers won't match.
If you don't do this, the JVM automatically generates a serialVersionUID for you based upon the class itself, so if you've changed certain things about the class, you may suddenly find that you have problems deserialising older versions of the class.

Categories