Using parsed input from text file as parameter for new Event - java

I've working on an assignment that asks me to alter a method in a class to take content from a textfile and use it to create multiple instances of various subclasses of the Event Class. Here is the text file:
Event=ThermostatNight,time=0
Event=LightOn,time=2000
Event=WaterOff,time=8000
Event=ThermostatDay,time=10000
Event=Bell,time=9000
Event=WaterOn,time=6000
Event=LightOff,time=4000
Event=Terminate,time=12000
The Event=* is the name of the subclass, while time=* is a parameter that is used in the subclass' constructor. The Event class itself is an abstract class and is used for inheritance.
public class Restart extends Event {
Class eventClass;
String eventInput;
Long timeDelay;
public Restart(long delayTime, String filename) {
super(delayTime);
eventsFile = filename;
}
public void action() {
List<String> examples = Arrays.asList("examples1.txt", "examples2.txt", "examples3.txt", "examples4.txt");
for (String example : examples) {
//finding pattern using Regex
Pattern pattern = Pattern.compile(example);
Matcher matcher1 = pattern.matcher(eventsFile);
if (matcher1.find()) {
File file = new File(example);
String line;
try {
FileReader fileReader = new FileReader(file);
Scanner sc = new Scanner(file);
BufferedReader bufferedReader =
new BufferedReader(fileReader);
while ((line = bufferedReader.readLine()) != null) {
sc.useDelimiter("\n");
//Parsing through text
while (sc.hasNext()) {
String s = sc.next();
String[] array1 = s.split(",");
String[] array2 = array1[0].split("=");
eventInput = array2[1];
String[] array3 = array1[1].split("=");
String timeInput = array3[1];
try {
eventClass = Class.forName(eventInput);
timeDelay = Long.parseLong(timeInput);
try {
addEvent(new eventClass(timeDelay));
}
//catch block
catch(NoSuchMethodException e){
System.out.println("No Such Method Error");
} catch (Exception e) {
System.out.println("error");
}
//catch block
} catch (ClassNotFoundException ex) {
System.out.println("Unable to locate Class");
} catch (IllegalAccessException ex) {
System.out.println("Illegal Acces Exception");
} catch (InstantiationException ex) {
System.out.println("Instantiation Exception");
}
}
}
//Close bufferedReader
bufferedReader.close();
}
//catch block
catch (FileNotFoundException ex) {
System.out.println(
"Unable to open file '" +
file + "'");
} catch (IOException ex) {
ex.printStackTrace();
}
break;
}
//if input match is not found
else {
System.out.println("No Match Found");}
}
}
I seem to be able to parse fine, and find the strings i'm looking for, but I'm not able to use eventInput which I've pulled from the text file as a parameter to create a new event.
eventClass = Class.forName(eventInput);
doesn't seem to be turning my string into an acceptable parameter either.
Any help would be much appreciated!
I know I'm probably missing something key here, but I've been staring at it too long that it seems like a lost cause.
Here is the Event class:
public abstract class Event {
private long eventTime;
protected final long delayTime;
public Event(long delayTime) {
this.delayTime = delayTime;
start();
}
public void start() { // Allows restarting
eventTime = System.currentTimeMillis() + delayTime;
}
public boolean ready() {
return System.currentTimeMillis() >= eventTime;
}
public abstract void action();
} ///:~

I think you've misunderstood how reflection works. Once you have a Class object (the output from Class.forName(), you have to find the appropriate constructor with
Constructor<T> constructor = eventClass.getConstructor(parameter types)
and then create a new instance with
constructor.newInstance(parameters);
For a no-arg constructor there's a shortcut
eventClass.newInstance();
I strongly suggest you read the tutorials on reflection before proceeding.

Related

How could I deal with this custom Exception?

I have this bit of code which depends from a custom Exception thrown by a function inside findID() it throws a NoClientFound Exception that I made whenever this mentioned function returns a null (The client does not exist).
The IDE suggests that I shall apply that Exception into the code, but in this bit of code, where I need the ID to be null (unique IDs) I "can't catch that exception" since if I catch it, the function will not be executed as intended.
Question: How I can manage this?
Function with the Exception problem
public boolean add(Client c) {
StringBuilder sb = new StringBuilder();
boolean added = false;
try {
if (findID(c.getID()) == null) {
try (BufferedWriter bw = new BufferedWriter(
new FileWriter(fitxer, true));) {
//Add client to file
bw.write(sb.append(c.getID()).append(SEPARADOR).
append(c.getName()).toString());
bw.newLine();//New line
bw.flush(); //Push to file
added = true;
} catch (IOException e) {
Logger.getLogger(DaoClient.class.getName()).log(Level.SEVERE,
null, "Error appeding data to file" + e);
}
}
} catch (IOException ex) {
Logger.getLogger(DaoClient.class.getName()).log(Level.SEVERE, null,
"Error appeding data to file" + ex);
} finally {
}
return addded;
}
Exception Code
public class NoClientFound extends Exception {
private String msg;
public NoClientFound() {
super();
}
public NoClientFound(String msg) {
super(msg);
this.msg = msg;
}
#Override
public String toString() {
return msg;
}
You can catch that exception and handle it accordingly. When you catch NoClientFound exception that means findID(c.getID()) is null. So without handling that in the if block you can handle that within the catch block.
public boolean add(Client c) {
StringBuilder sb = new StringBuilder();
boolean added = false;
try {
// call the function
findID(c.getID());
} catch (NoClientFound ex) {
//handle the NoClientFound exception as you like here
BufferedWriter bw = new BufferedWriter(
new FileWriter(fitxer, true));
//Add client to file
bw.write(sb.append(c.getID()).append(SEPARADOR).
append(c.getName()).toString());
bw.newLine();//New line
bw.flush(); //Push to file
added = true;
}catch (IOException ex) {
Logger.getLogger(DaoClient.class.getName()).log(Level.SEVERE, null,
"Error appeding data to file" + ex);
}finally {
}
return addded;
}
I assume you already have a null check on findID(...)
if( c == null || findID(c.getID()) == null){
throw new NoClientFound("Client not found!");
}else{
//add your file writing operation
}
and Also in NoClientFound class extend it from RuntimeException, not the Exception.
public class NoClientFound extends RuntimeException {
...
}
Caller method:
public void caller(){
Client client = new Client();
client.setId(1);
...
try{
add(client);
}catch(NoClientFound ex){
//client not found then create one for ex...
}
catch(Exception ex){
//somthing else happend
log.error(ex.getmessge());
}
}

Why i can't open second stream in java?

Here is my problem.I've made simple input class with methods for getting primitive values from user's keyboard.The problem is that whenever i use this class in my other classes i face the problem that when i made more than one instance of this class i get a problem of the "Close stream".Why is this happening?
For example:i have a main method where i get user's input and decide which object to make,say i can make 4 different objects(4 classes),after i call the objects "set state" method,where i actually set all the states of this object with making second instance of the input class,and then ,when i try to read again the user's input in my main method,i get an exception "Stream closed".
Here is the code of the input class :
public class UserInput {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));;
public int getInt() {
try {
String line;
line = reader.readLine();
return Integer.parseInt(line);
} catch (Exception ex) {
ex.printStackTrace();
return -1;
}
}
public double getDouble() {
try {
String line = reader.readLine();
return Double.parseDouble(line);
} catch (Exception ex) {
return -1;
}
}
public float getFloat() {
try {
String line = reader.readLine();
return Float.parseFloat(line);
} catch (Exception ex) {
return -1;
}
}
public long getLong() {
try {
String line = reader.readLine();
return Long.parseLong(line);
} catch (Exception ex) {
return -1;
}
}
public short getShort() {
try {
String line = reader.readLine();
return Short.parseShort(line);
} catch (Exception ex) {
return -1;
}
}
public String getString() {
try {
String line = reader.readLine();
return line;
} catch (Exception ex) {
return " ";
}
}
public char getChar() {
try {
return (char) reader.read();
} catch (Exception ex) {
return (' ');
}
}
public void close() {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
The standard way for user input is to use a Scanner which already contains methods for reading different kinds of input.
You're not supposed to close the reader, because that will then close System.in which is not what you want.
By calling reader.close(); you are not only closing the reader himself because the call invokes the close() method of the InputStreamReader aswell and therefore closes System.in (which you can not reopen).
A possible Solution would be to use a Scanner as Kayaman pointed out in his answer or to override the close() method like this:
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in){#Override public void close(){});

Java: lists, bufferedScanner and Error: java.lang.NullPointerException

I keep getting the error message Error: java.lang.NullPointerException at runtime. Obviously I understand that this shows when I am referencing some variable that has a null value when it should have some value. Thought it best to show you the code so I can put it into context.
public class MarathonAdmin
{
private List<Runner> runners;
/**
* Constructor for objects of class MarathonAdmin
*/
public MarathonAdmin()
{
// initialise instance variables
List<Runner> runners = new ArrayList<>();
}
public void readInRunners()
{
String pathName = OUFileChooser.getFilename();
File aFile = new File(pathName);
Scanner bufferedScanner = null;
try
{
String runnerName;
int runnerAge;
String ageGroup;
Scanner lineScanner;
String currentLine;
bufferedScanner = new Scanner(new BufferedReader(new FileReader(aFile)));
while (bufferedScanner.hasNextLine())
{
currentLine = bufferedScanner.nextLine();
lineScanner = new Scanner(currentLine);
lineScanner.useDelimiter(",");
runnerName = lineScanner.next();
runnerAge = lineScanner.nextInt();
Runner runnerObject = new Runner();
if (runnerAge < 18)
{
ageGroup = "junior";
runnerObject.setAgeGroup(ageGroup);
}
else
if (runnerAge > 54)
{
ageGroup = "senior";
runnerObject.setAgeGroup(ageGroup);
}
else
{
ageGroup = "standard";
runnerObject.setAgeGroup(ageGroup);
}
runnerObject.setName(runnerName);
runners.add(runnerObject);
}
}
catch (Exception anException)
{
System.out.println("Error: " + anException);
}
finally
{
try
{
bufferedScanner.close();
}
catch (Exception anException)
{
System.out.println("Error: " + anException);
}
}
}
The test code to create an instance of the class is:
MarathonAdmin ma = new MarathonAdmin();
ma.readInRunners();
There is a class in use called Runners which is already set up with its protocols. The class compiles but the ma.readInRunner(); message ends in an error. The text file that the program is to run from has no errors.
I'm somewhat new to programming and so find it hard to troubleshoot issues. Hopefully someone can help me out.
In the constructor it should be
public MarathonAdmin()
{
// initialise instance variables
this.runners = new ArrayList<>();
}
and not
public MarathonAdmin()
{
// initialise instance variables
List<Runner> runners = new ArrayList<>();
}
The problem is that you have made a Try-catch block, but in the catch part you are not printing the stacktrace, see:
catch (Exception anException)
{
System.out.println("Error: " + anException); // just prints: Error: java.lang.NullPointerException
}
Improve this catch block for debugging, for example like this:
catch (Exception e) {
e.printStackTrace(); //prints the full stacktrace
}
Now you should get a full stacktrace that also shows you the line number and you will be able to debug it yourself ;-)
In fact you probably should remove that try-catch blocks at all.

Java Serialization

I'm learning now how to do serialization using Java Language. I have read some posts and docs about the subject and I tried to do a simple example (below)
public class SterializeObject implements java.io.Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
private String name;
private transient int code;
public SterializeObject (String n, int c){
name = n;
code = c;
}
public void printAtributes (){
System.out.println("name: " + name + "; code: " + code);
}
}
public class MainClass {
public static void main(String[] agrs) {
SterializeObject ob1 = new SterializeObject("ana", 1);
SterializeObject ob2 = new SterializeObject("rita", 2);
try {
FileOutputStream fileOut = new FileOutputStream("file.data");
ObjectOutputStream outObj = new ObjectOutputStream(fileOut);
outObj.writeObject(ob1);
outObj.writeObject(ob2);
outObj.close();
System.out.println("Objects were serialized!");
} catch (IOException e) {
e.printStackTrace();
}
ArrayList<SterializeObject> list = new ArrayList<SterializeObject>();
try {
FileInputStream fileInput = new FileInputStream("file.data");
ObjectInputStream inputObj = new ObjectInputStream(fileInput);
Object o;
try {
while ((o = inputObj.readObject()) != null) {
list.add((SterializeObject) o);
}
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("Erro foi aqui! (1)");
}
inputObj.close();
fileInput.close();
} catch (IOException e) {
e.printStackTrace();
System.out.println("Erro foi aqui! (2)");
}
for (int i = 0; i < list.size(); ++i) {
list.get(i).printAtributes();
}
}
}
I created a Class SterializeObject that implements java.io.Serializable with two variables: one string (name) and one int (code) that is transient. Then In the main I generate two instances of that class and I tried to write it in a file, that I have done successfully! After that, I try to read the two object with a Loop.. there is my problem.. since the ObjectInputStream dosen't have some kind of method to see if we are in the end or not. So, I tried to do with this condition: (o = inputObj.readObject()) != null.
My output is this:
java.io.EOFException
at java.io.ObjectInputStream$BlockDataInputStream.peekByte(Unknown Source)
at java.io.ObjectInputStream.readObject0(Unknown Source)
at java.io.ObjectInputStream.readObject(Unknown Source)
at MainClass.main(MainClass.java:30)
Objects were serialized!
Erro foi aqui! (2)
name: ana; code: 0
name: rita; code: 0
I get the objects, but I get an error because, I think, is trying to access to something that doesn't exist.
Someone can tell me other way to do it?
Best Regards.
Read as many objects as the number of written objects, or write the list of objects itself, instead of writing every object one after the other.
(Or rely on the EOFException to detect the end of the stream, but this is ugly).
As many of you told me to do, I created a ArrayList and serialized the ArrayList.
My code is:
public class MainClass {
public static void main(String[] agrs) {
SterializeObject ob1 = new SterializeObject("ana", 1);
SterializeObject ob2 = new SterializeObject("rita", 2);
ArrayList <SterializeObject> list = new ArrayList<>();
list.add(ob1);
list.add(ob2);
ArrayList <SterializeObject> input = new ArrayList<SterializeObject>();
try {
FileOutputStream fileOut = new FileOutputStream("file.data");
ObjectOutputStream outObj = new ObjectOutputStream(fileOut);
outObj.writeObject(list);
outObj.close();
System.out.println("Objects were serialized!");
} catch (IOException e) {
e.printStackTrace();
}
try {
FileInputStream fileInput = new FileInputStream("file.data");
ObjectInputStream inputObj = new ObjectInputStream(fileInput);
Object o;
try {
input = (ArrayList<SterializeObject>) inputObj.readObject();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("Erro foi aqui! (1)");
}
inputObj.close();
fileInput.close();
} catch (IOException e) {
e.printStackTrace();
System.out.println("Erro foi aqui! (2)");
}
for (int i = 0; i < input.size(); ++i) {
input.get(i).printAtributes();
}
}
}
And the output is:
Objects were serialized!
name: ana; code: 0
name: rita; code: 0
Thank you for the help!
Close the FileOutputStream also along with ObjectOutputStream
fileOut.close();
Why don't you add both object to an ArrayList, and serialize the ArrayList. Then you just have to Deserialize the ArrayList and it will be populated with both objects.
You can do this by placing the readObject call inside a try-catch block and catching that EOFException you get, signaling you have read all the objects.
Replace your while loop with this piece of code
do{
try
{
o = inputObj.readObject();
list.add((SterializeObject) o);
}
catch(EOFException e)
{
o = null;
}
}while (o != null);

Program in java that reads data from a text file

date time kg
12/10/2013 00.00.01 1
13/11/2013 00.00.05 2
17/12/2013 00.00.90 5
21/12/2013 00.00.23 6
27/12/2013 00.00.43 9
I have these data in an txt file. I would like to make o program in java that would read these data. I ' ve written the code above but I have mistakes. Could someone help me? The data have space between each other.
import java.io*;
public class ReadTextfile{
public static void main (String[] args) {
File file = new File ("test.txt");
StringBuilder line = new StringBuilder();
BufferedReader reader = null;
try {
reader = new BufferedReader (new FileReader(file));
String text = null;
while ((text = reader.readLine()) !=null) {
line.append(text)
.append(System.getProperty ("line.separator"));
}
}
catch (IOException e) {
e.printStackTrace();
catch (FileNotFoundException e) {
e.printStackTrace();
}finally {
try {
if (reader !=null){
reader.close();
}
}
catch (IOException e) {
e.printStackTrace();
}
}
System.out.println(line.toString());
}
}
boy you are only having some syntax problem
1 : replace
import java.io* with import java.io.*
2 : take care of your catch body being started and closed properly
try
{
// your code
}
catch(Exception e)
{
}
here is the working code , compare your program
import java.io.*;
public class ReadTextfile{
public static void main (String[] args)
{
File file = new File ("C:/Users/hussain.a/Desktop/test.txt");
StringBuilder line = new StringBuilder();
BufferedReader reader = null;
try {
reader = new BufferedReader (new FileReader(file));
String text = null;
while ((text = reader.readLine()) !=null) {
line.append(text)
.append(System.getProperty ("line.separator"));
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally
{
try {
if (reader !=null){
reader.close();
}
}
catch (IOException e)
{
e.printStackTrace();
}
}
System.out.println(line.toString());
}
}
catch (FileNotFoundException e)
This is unreachable code, since above it you caught IOException.
Note that:
public class FileNotFoundException extends IOException
Your code won't compile. Remove this catch (You didn't even close it..)
Another thing, if this is not a type, you should replace java.io* with import java.io.*.
I would take the following approach:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class ReadTextFile
{
public static void main(String[] args) throws FileNotFoundException
{
File file = new File("test.txt");
Scanner scanner = new Scanner(file);
List<Result> results = new ArrayList<Result>();
while(scanner.hasNextLine())
{
String currentLine = scanner.nextLine();
String [] resultArray = currentLine.split(" ");
results.add(new Result(resultArray[0], resultArray[1], resultArray[2]));
}
scanner.close();
}
private static class Result
{
private String date;
private String time;
private String kg;
public Result(String date, String time, String kg)
{
super();
this.date = date;
this.time = time;
this.kg = kg;
}
public String getDate()
{
return date;
}
public String getTime()
{
return time;
}
public String getKg()
{
return kg;
}
}
}
Now you can pull out any information that you want to from the list of results that you have.
So if you wanted to print everything, you could do the following:
for(Result singleResult : results)
{
System.out.println(singleResult.getDate() + " " + singleResult.getTime() + " " + singleResult.getKg());
}
You basically can do whatever you want to with the data. This approach would also allow you to transform the data into different types before you even create the Result object.

Categories

Resources