I have a slightly more advanced class I am trying to write a toString() for
in order to accomplish what I am trying to do I need to be able to change the assignment of certain variables when doing toString().
TO make it simple I am going to remove a bunch of stuff except what allows it to work.
public enum PacketElementType {
NONE((byte)0, "None"),
BYTE((byte)1, "Byte"),
SHORT((byte)2, "Short"),
INT((byte)3, "Int"),
LONG((byte)4, "Long"),
FLOAT((byte)5, "Float"),
STRING((byte)6, "String"),
BIN((byte)7, "Bin");
private final byte typeValue;
private final String typeName;
PacketElementType(byte type, String name)
{
this.typeValue = type;
this.typeName = name;
}
public String getTypeName() {
return typeName;
}
public byte getTypeValue() {
return typeValue;
}
}
public class Packet {
private final int DEFAULT_SIZE = 1024 * 2;
private final int ADD_SIZE = 1024;
private byte[] _buffer = new byte[1];
private int _ptr = 0;
private int _bodyStart = 0;
private int _elements, _bodyLen = 0;
private int op;
private long id;
public Packet(int op, long id) {
setOp(op);
setId(id);
_buffer = new byte[DEFAULT_SIZE];
}
public int getOp() {
return op;
}
public void setOp(int op) {
this.op = op;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public PacketElementType peek() {
int pie = _ptr;
if (pie + 2 > _buffer.length)
return PacketElementType.NONE;
return PacketElementType.values()[_buffer[_ptr]];
}
protected Packet putSimple(PacketElementType type, byte... val) {
int len = val.length + 1;
this.ensureSize(len);
_buffer[++_ptr] = type.getTypeValue();
System.arraycopy(val, 0, _buffer, _ptr, val.length);
_ptr += val.length;
_elements++;
_bodyLen += len;
return this;
}
public Packet putByte(byte val) {
return this.putSimple(PacketElementType.BYTE, val);
}
public Packet putByte(boolean val) {
return this.putByte(val ? (byte) 1 : (byte) 0);
}
public byte getByte() throws Exception {
if (this.peek() != PacketElementType.BYTE)
throw new Exception("Expected Byte, got " + this.peek().getTypeName() + ".");
_ptr += 1;
return _buffer[++_ptr];
}
protected void ensureSize(int required) {
if (_ptr + required >= _buffer.length) {
byte[] b = new byte[_buffer.length + Math.max(ADD_SIZE, required * 2)];
System.arraycopy(_buffer, 0, b, 0, _buffer.length);
_buffer = b;
}
}
private boolean isValidType(PacketElementType type)
{
return (type.getTypeValue() >= PacketElementType.BYTE.getTypeValue() && type.getTypeValue() <= PacketElementType.BIN.getTypeValue());
}
protected String toStringHack()
{
StringBuilder result = new StringBuilder();
int prevPtu = _ptr;
_ptr = _bodyStart;
try {
result.append(String.format("Op: %1$08d %3$s, Id: %2$016d\r\n", this.getOp(), this.getId(), Op.getName(this.getOp())));
} catch (IllegalAccessException e) {
e.printStackTrace();
return result.append("Failed to convert packet to string").toString();
}
PacketElementType type;
for (int i = 1; (this.isValidType(type = this.peek()) && _ptr < _buffer.length); ++i)
{
if (type == PacketElementType.BYTE)
{
byte data = 0;
try {
data = getByte();
} catch (Exception e) {
e.printStackTrace();
result.append("Failed to parse element at position ").append(i);
continue;
}
result.append(String.format("%1&03d [%2$s] Byte : %3$s", i, String.format("%1$016d", data), data));
}
}
return result.toString();
}
//TODO: toString
#Override
public String toString()
{
return toStringHack();
}
}
public class Op {
public class Msgr
{
}
public static String getName(int op) throws IllegalAccessException {
for (Field field : Op.class.getFields())
{
if ((int)field.get(null) == op)
return field.getName();
}
for (Field field : Op.Msgr.class.getFields())
{
if ((int)field.get(null) == op)
return field.getName();
}
return "?";
}
}
[2
When debugging, _ptr won't set in toString(), when not debugging, _ptr won't set in putSimple().
I'm so close to pulling my hair out, please and thanks, if you could help me I would really be glad! Please and thank you again!
To test for this bug please review the following example:
Packet p = new Packet(1, 10001).putByte(true);
Toast.makeText(this, p.toString(), Toast.LENGTH_LONG).show();
for me I throw this inside the built in test class first, and then tried it in the onCreate from the main activity.
toString() will only return the Op and Id because _ptr is at , peek() will attempt to read the byte starting at that position instead of at 0 where it would find our 1 byte.
Edit
It seems like... _ptr = _bodyStart; is being seen as something other than an assignment, is this possible?
Result you see is ok - debugger shows you those variables before evaluation. Ad a line after this one (like a log or smth.) and set breakpoint on it.
so it turns out I was missing just one small tiny little details..... Not tiny at all, I apologize for not seeing this earlier. toString() would fail because of a malformed String.format() call as well as the failure to set ptr back to it's original value after toString() was completed.
result.append(String.format("%1&03d [%2$s] Byte : %3$s", i, String.format("%1$016d", data), data));
Should have been (where right after %1 I had an & instead of a $)
String hello = String.format("%1$03d [%2$s] Byte : %3$d\r\n", i, StringUtils.leftPad(String.format("%02X", data), 16, '.'), (int) data);
and just before returning the string, I needed to do the following
ptr = prevPtu;
with that, the following happens:
Related
I have an input file stream method that will load a file, I just can't figure out how to then use the file in another method. The file has one UTF string and two integers. How can I now use each of these different ints or strings in a main method? Lets say I want print the three different variables to the console, how would I go about doing that? Here's a few things I've tried with the method:
public static dataStreams() throws IOException {
int i = 0;
char c;
try (DataInputStream input = new DataInputStream(
new FileInputStream("input.dat"));
) {
while((i=input.read())!=-1){
// converts integer to character
c=(char)i;
}
return c;
return i;
/*
String stringUTF = input.readUTF();
int firstInt = input.readInt();
int secondInt = input.readInt();
*/
}
}
Maybe one container for those properties, like this:
public static void main(String [] args) {
DataContainer dContainer = null;
try {
dContainer = dataStreams();
} catch (IOException e) {
e.printStackTrace();
}
//do some logging with properties
System.out.println(dContainer.getFirst());
System.out.println(dContainer.getSecond());
System.out.println(dContainer.getUtf());
}
public static DataContainer dataStreams() throws IOException {
int i = 0;
char c;
try (DataInputStream input = new DataInputStream(
new FileInputStream("input.dat"));
) {
while((i=input.read())!=-1){
// converts integer to character
c=(char)i;
}
String stringUTF = input.readUTF();
int firstInt = input.readInt();
int secondInt = input.readInt();
DataContainer dContainer = new DataContainer(stringUTF, firstInt, secondInt);
return dContainer;
}
}
static class DataContainer {
String utf;
int first;
int second;
DataContainer(String utf, int first, int second) {
this.utf = utf;
this.first = first;
this.second = second;
}
public String getUtf() {
return utf;
}
public int getFirst() {
return first;
}
public int getSecond() {
return second;
}
}
I am currently working on a "code parser" parsing Valve Map Format (.vmf files) into a java readable Object.
In vmf files,
there are 2 types of objects: Classes and Properties.
classes have a name and can contain other classes and properties.
properties have a name and an unlimited number of values.
Therefore I created a VMFClass Object Class and a VMFProperty Object Class.
I created a List with self-created HierarchyObjects, containing the VMFClass/VMFProperty Object, an UUID and the parentUUID.
The VMFClass Object Contains 2 Lists one with sub-VMFClasses, one with properties.
My Problem is that I have no clue on how to achieve that a Class contains all of its subclasses, since I can't tell how much subclasses the subclasses have and so on...
Here is my Code (Github):
HierachyObject:
package net.minecraft.sourcecraftreloaded.utils;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class HierarchyObject {
private static Map<Long, Long> usedUUIDs = new HashMap<>();
private long parentUUID;
private long UUID;
private Object object;
/**
*
* #param Object
* #param parent -1 is maximum level
*/
public HierarchyObject(Object object, long parent) {
this.object = object;
this.parentUUID = parent;
while (true) {
long random = (long) (Math.random() * Long.MAX_VALUE);
if (usedUUIDs.containsKey(random)) {
this.UUID = random;
usedUUIDs.put(random, parent);
break;
}
}
}
public long getUUID() {
return UUID;
}
public long getParentUUID() {
return parentUUID;
}
public static long getParentUUIDbyUUID(long UUID) {
if (usedUUIDs.containsKey(UUID)) {
return usedUUIDs.get(UUID);
}
return -1;
}
public Object getObject() {
return object;
}
public static boolean hasChild(long UUID){
if(usedUUIDs.containsValue(UUID)){
return true;
}
if(UUID == -1){
return true;
}
return false;
}
public boolean hasChild(){
return hasChild(this.UUID);
}
public static long[] getChildUUIDs(long UUID){
if(hasChild(UUID)){
List<Long> cUUIDs = new ArrayList<>();
for(int i = 0; i < usedUUIDs.size(); i++){
for (Map.Entry<Long, Long> e : usedUUIDs.entrySet()) {
if(e.getValue().longValue() == UUID){
cUUIDs.add(e.getKey());
}
}
}
return ListUtils.toPrimitivebyList(cUUIDs);
}
return null;
}
}
VMFProperty:
package net.minecraft.sourcecraftreloaded.source;
public class VMFProperty{
private String name;
private String[] values;
public VMFProperty(String name, String... values) {
this.name = name;
this.values = values;
}
public String getName() {
return name;
}
public String[] getValues() {
return values;
}
#Override
public boolean equals(Object paramObject){
if(paramObject instanceof VMFProperty){
return ((VMFProperty)paramObject).name.equals(this.name) && ((VMFProperty)paramObject).values.equals(this.values);
}
return false;
}
}
VMFClass:
package net.minecraft.sourcecraftreloaded.source;
import java.util.List;
public class VMFClass{
private List<VMFClass> classes;
private List<VMFProperty> properties;
private String name;
public VMFClass(String name, List<VMFClass> classes, List<VMFProperty> properties) {
this.name = name;
this.classes = classes;
this.properties = properties;
}
public String getName() {
return name;
}
public List<VMFClass> getClasses() {
return classes;
}
public List<VMFProperty> getProperties() {
return properties;
}
public void add(VMFClass vmfclass) {
classes.add(vmfclass);
}
public void add(VMFProperty vmfproperty) {
properties.add(vmfproperty);
}
public void remove(VMFClass vmfclass) {
classes.remove(vmfclass);
}
public void remove(VMFProperty vmfproperty) {
properties.remove(vmfproperty);
}
#Override
public boolean equals(Object paramObject){
if(paramObject instanceof VMFClass){
return ((VMFClass)paramObject).properties.equals(this.properties) && ((VMFClass)paramObject).classes.equals(this.classes) && ((VMFClass)paramObject).name.equals(this.name);
}
return false;
}
}
VMFObject (the class executing all the code):
package net.minecraft.sourcecraftreloaded.source;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import net.minecraft.sourcecraftreloaded.utils.HierarchyObject;
public class VMFObject {
private String rawfile = "";
private List<VMFClass> toplevelclasses;
private static final String INVALID_CHARS = "\\*,;<>|?=`´#'+~^°!§$%&()[].:-_";
public VMFObject(List<VMFClass> toplevelclasses) {
this.toplevelclasses = toplevelclasses;
}
public VMFObject() {
this(new ArrayList<VMFClass>());
}
public void write(File file) {
VMFWriter.write(file, rawfile);
}
public VMFObject read(File file) throws VMFParsingException {
this.rawfile = VMFReader.read(file);
parse();
return this;
}
public List<VMFClass> getClasses() {
return toplevelclasses;
}
private void parse() throws VMFParsingException {
evaluate();
get();
}
private void evaluate() throws VMFParsingException {
char[] textchars = rawfile.toCharArray();
int[] c = new int[]{0, 0, 0};
int line = 0;
int linepos = 0;
for (int i : textchars) {
linepos++;
if (textchars[i] == '\n') {
line++;
linepos = 0;
c[3] = 0;
if (c[3] % 2 != 0) {
throw new VMFParsingException("Invalid quotes on line" + line + ":" + linepos);
}
}
if (textchars[i] == '{') {
c[1]++;
}
if (textchars[i] == '}') {
c[2]++;
}
if (textchars[i] == '"') {
c[3]++;
if (c[1] - c[2] == 0) {
}
}
if (textchars[i] == '/' && textchars[i + 1] == '/') {
while (true) {
i++;
if (textchars[i] == '\n') {
break;
}
}
}
if (textchars[i] == '/' && textchars[i + 1] == ' ') {
throw new VMFParsingException("Invalid Character '/' on line" + line + ":" + linepos);
}
if (INVALID_CHARS.indexOf(textchars[i]) != -1) {
throw new VMFParsingException("Invalid Character '" + textchars[i] + "' on line" + line + ":" + linepos);
}
}
if (c[1] != c[2]) {
throw new VMFParsingException("Unbalanced brackets in vmf File");
}
}
public void add(VMFClass vmfclass) {
toplevelclasses.add(vmfclass);
}
private void get() throws VMFParsingException {
List<HierarchyObject> content = new ArrayList<>();
long curparent = -1;
String[] text = rawfile.split("\n");
for (int i = 0; i < text.length; i++) {
String line = text[i].trim();
if (line.startsWith("//")) {
continue;
} else {
byte quotec = 0;
char[] linechar = line.toCharArray();
boolean readp = false;
List<String> reads = new ArrayList<>();
byte creads = 0;
for (int y = 0; y < linechar.length; y++) {
if (linechar[y] == '/' && linechar[y + 1] == '/') {
break;
}
if (linechar[y] == '"') {
quotec++;
if (quotec % 2 == 0) {
readp = false;
creads++;
} else {
readp = true;
}
}
if (readp) {
reads.set(creads, reads.get(creads) + linechar[y]);
}
if (linechar[y] == '{') {
HierarchyObject object = new HierarchyObject(new VMFClass(line.substring(line.substring(0, y).lastIndexOf(' '), y).trim(), null, null), curparent);
content.add(object);
curparent = object.getUUID();
}
if (linechar[y] == '}') {
curparent = HierarchyObject.getParentUUIDbyUUID(curparent);
}
}
content.add(new HierarchyObject(new VMFProperty(reads.remove(0), reads.toArray(new String[reads.size()])), curparent));
}
}
buildObject(content);
}
private void buildObject(List<HierarchyObject> content) {
long curUUID = -1;
for(int i = 0; i < HierarchyObject.getChildUUIDs(curUUID).length; i++){
HierarchyObject.getChildUUIDs(curUUID);
}
//TODO implement
}
}
the //TODO part is where the Hierachy Object should get "converted" to the actual object.
Overview
It seems to me that your class layout is overcomplicated.
Let's try to simplify it...
What you have described with the VMF model is essentially a linked-list Tree.
Here's what the model looks like:
[.vmf file] (root)
/ \
_____/ \ _____
/ \
/ \
(VMFClass) (VMFClass)
/ \ / \
/ \ / \
/ \ / \
(VMFClass) (VMFProperties) (VMFClass) (VMFProperties)
/ \
/ \
/ \
(VMFClass) (VMFProperties)
What you need:
A Parser class (in your case, you have VMFObject, but lets call this class VMFParser).
The VMFClass and VMFProperty classes which you have are fine.
What you don't need:
The HierarchyObject class. The VMFParser can be the main controller and container for the hierarchy (e.g. the linked-list Tree model).
All the UUIDs (parent, child, etc.) These are just complicated things, but I see why you have them. You don't need them to track the hierarchy - Java will do this for us!!
VMFClass
public class VMFClass
{
// name of the class
private String name;
// reference back up to the parent
private VMFClass parentClass = null;
// all direct children go here
private List<VMFClass> children = new ArrayList<VMFClass>();
// I don't think you need a list of properties here since your VMFProperty class holds onto an array of properties
private VMFProperty properties;
// set the parent of this class
public void setParent (VMFClass parent)
{
this.parentClass = parent;
}
// get the direct children
public List<VMFClass> getChildren()
{
return this.children;
}
// rest of methods...
}
VMFParser
class VMFParser
{
private String rawfile = "";
// this is really the container for everything - think of it as the file shell
private VMFClass root = new VMFClass("root", null, null);
// construct yourself with the file
public VMFParser (String fileName)
{
this.rawfile = fileName;
}
public void parse ()
{
// all the parsing code goes here
read();
evaluate();
get();
// now at this point your hierarchy is built and stored in the
// root object in this class.
// Use the traverse method to go through it
}
private void get() throws VMFParsingException
{
// keep a reference to the current VMFClass parent
// starts out as root
VMFClass currParentClass = root;
// main parse loop
for (...)
{
// if you find a class
VMFClass currClass = new VMFClass(/* params here */);
// add this class to the parent
currParentClass.add(currClass);
// set the parent of this class
currClass.setParent(currParentClass);
// if you find a property
// parse and add all the properties to the property
VMFProperty property = new VMFProperty (/* value params here */);
// attach this property to the last VMF class that got parsed
currClass.setPoperties(property);
// If you nest deeper into classes, then the parent becomes the current class
currParentClass = currClass;
// If you go back out of a class
currParentClass = currClass.getParent();
}
}
// Traverse the hierarchy
public void traverse ()
{
traverseTree(root);
}
private void traverseTree (VMFClass root)
{
System.out.println("Class Name: " + root.getName());
// print out any properties
VMFProperty prop = root.getProperty();
if (prop != null)
{
System.out.println("Property Name: " + prop.getName());
String [] props = prop.getValues();
for (String s: props)
{
System.out.println("Value: " + s);
}
}
// get all child classes
List<VMFClass> children = root.getChildren();
for (VMFClass c: children)
{
traverseTree(c);
}
}
}
Client Code
Example
public static void main(String[] args)
{
VMFParser vmfParser = null;
try
{
vmfParser = new VMFParser("myFile.vmf");
vmfParser.parse();
// access the vmfParser for the hierarchy
vmfParser.traverse();
}
catch (VMFParsingException vpe)
{
// do something here
vpe.printStackTrace();
}
finally
{
// clean up...
}
}
If you are just looking to find all sub classes of particular class or interface , this might help you,
How can I get a list of all the implementations of an interface programmatically in Java?
I am working on a project with a datatructure that is deeper than 1 level and I try to box different user-defined datatypes to hold information of all levels.
First Level: A class that has only an ArrayList of level 2 datatype and some functions to access the data of all Levels.
Second Level: A class that has some standard variables and an ArrayList of Level 3 datatype and also some functions .
Third Level: A class / record of some standard variables
The instance of the first-level datatype should be used by more than one activity of my application (almost all).
Here is my problem: I can initialize the first-level and add some objects to the list, but I could not do so with the second level. If I add some object in the list of the second level all seems to be good, but when I access this data a NullPointerException occurs.
Here is my question: Is it possible to box datatypes in more than 1 level? And where I should search for the error.
For better understanding the sources:
modulData.java (First Level)
package de.myApp.dataholder;
import java.util.ArrayList;
import android.util.Log;
public class modulData {
// Constructor
private static final modulData mainModulDataHolder = new modulData();
public static modulData getInstance() {return mainModulDataHolder;}
// Data
private ArrayList<isModulData> mIsModulData;
// Functions
public void init() {
this.mIsModulData = new ArrayList<isModulData>();
}
public isModulData getModul(int mID) {
isModulData result = null;
int i;
for (i = 0; i < mIsModulData.size(); i++) {
if (mIsModulData.get(i).ID() == mID) {
result = mIsModulData.get(i);
break;
}
}
return result;
}
public isCatData getCategory(int mID, int cID) {
isCatData result = new isCatData();
isCatData buffer = new isCatData();
int i,j ;
for (i = 0; i < mIsModulData.size(); i++) {
if (mIsModulData.get(i).ID() == mID) {
for(j = 0; j < mIsModulData.get(i).CountCategorys(); j++) {
buffer = mIsModulData.get(i).getCategory(j);
if (buffer.ID() == cID) {
result = buffer;
break;
}
}
}
}
return result;
}
public int ModulCount() {
int result = 0;
if (mIsModulData != null) { result = mIsModulData.size(); }
return result;
}
public int CategoryCount(int mID) {
int result = -1;
int i;
for (i = 0; i < mIsModulData.size(); i++) {
if (mIsModulData.get(i).ID() == mID) {
result = mIsModulData.get(i).CountCategorys();
break;
}
}
return result;
}
public int addModulWithJSON(String jsonString) {
int result = -1;
isModulData newModul = new isModulData();
newModul.initCategorys();
if (mIsModulData == null) { this.init(); }
result = newModul.decodeFromJSON(jsonString);
mIsModulData.add(newModul);
return result;
}
public int addCategoryWithJSON(int mID, String jsonString) {
int result = -1;
int i;
for (i = 0; i < mIsModulData.size(); i++){
if (mIsModulData.get(i).ID() == mID) {
result = mIsModulData.get(i).addCategoryWithJSON(jsonString);
Log.i("AddCategoryWithJSON","Add Category "+ String.valueOf(result));
// Here is the Problem: Added but no access to Data. Null Object reference !!!!
Log.i("AddCategoryWithJSON", mIsModulData.get(mID).getCategory(result).Title());
break;
}
}
return result;
}
}
isModulData.java (second level)
package de.myApp.dataholder;
import java.util.ArrayList;
import org.json.JSONArray;
import org.json.JSONException;
import android.util.Log;
public class isModulData {
// Constructor
private static final isModulData modulDataHolder = new isModulData();
public static isModulData getInstance() {return modulDataHolder;}
// Data
private ArrayList<isCatData> mIsCatData;
private int mID;
private String mTitle;
private boolean misActive;
private int mBackgroundID;
// Functions
public int ID() { return this.mID; }
public String Title() { return this.mTitle; }
public boolean ActiveState() { return this.misActive; }
public int BackgroundID() { return this.mBackgroundID; }
public int decodeFromJSON(String jsonString) {
int result;
try {
JSONArray jArray = new JSONArray(jsonString);
this.mID = Integer.parseInt(jArray.getString(0).toString());
this.mTitle = jArray.getString(1).toString();
this.misActive = Boolean.parseBoolean(jArray.getString(2).toString());
this.mBackgroundID = Integer.parseInt(jArray.getString(3).toString());
result = this.mID;
} catch (JSONException e) {
e.printStackTrace();
Log.w("JSONDecode CMD801","Decode raised in JSONException ["+e.toString()+"]");
result = -1;
}
return result;
}
public int addCategoryWithJSON(String jsonString) {
int result = -1;
if (this.mIsCatData == null) { this.initCategorys(); }
isCatData cNewCategory = new isCatData();
result = cNewCategory.decodeFromJSON(jsonString);
this.mIsCatData.add(cNewCategory);
return result;
}
public isCatData getCategory(int cID) {
isCatData result = new isCatData();
if (cID < mIsCatData.size() -1) {
result = mIsCatData.get(cID);
} else {
result = null;
}
return result;
}
public void initCategorys() {
this.mIsCatData = new ArrayList<isCatData>();
}
public int CountCategorys() {
return this.mIsCatData.size();
}
}
isCatData.java (third level)
package de.myApp.dataholder;
import org.json.JSONArray;
import org.json.JSONException;
import android.util.Log;
public class isCatData {
// Constructor
private static final isCatData catDataHolder = new isCatData();
public static isCatData getInstance() {return catDataHolder;}
// Data
private int cID;
private String cTitle;
private boolean cisActive;
private boolean cisWriteEnable;
private int cBackgroundID;
// Functions
public int ID() { return this.cID; }
public String Title() { return this.cTitle; }
public boolean ActiveState() { return this.cisActive; }
public boolean WriteEnableState() { return this.cisWriteEnable; }
public int BackgroundID() { return this.cBackgroundID; }
public int decodeFromJSON(String jsonString) {
int result;
try {
JSONArray jArray = new JSONArray(jsonString);
this.cID = Integer.parseInt(jArray.getString(0).toString());
this.cTitle = jArray.getString(1).toString();
this.cisActive = Boolean.parseBoolean(jArray.getString(2).toString());
this.cisWriteEnable = Boolean.parseBoolean(jArray.getString(3).toString());
this.cBackgroundID = Integer.parseInt(jArray.getString(4).toString());
result = this.cID;
} catch (JSONException e) {
e.printStackTrace();
Log.w("JSONDecode CMD801","Decode raised in JSONException ["+e.toString()+"]");
result = -1;
}
return result;
}
}
My goal: save one ArrayList to a .dat file, after read this file and in the end print this array.
To save the ArrayList, "equipas" is one ArrayList< Equipa>, I use this function:
saveMyFile("Equipas.dat", (Object) equipas);
To read:
public static ArrayList<Equipa> readMyFile(String s){
ArrayList<Equipa> novo = new ArrayList<Equipa>();
try {
ObjectInputStream ois = new ObjectInputStream(new FileInputStream(s));
novo = (ArrayList<Equipa>) ois.readObject();
ois.close();
}
catch(IOException er) { System.out.println(er.getMessage()); }
catch(ClassNotFoundException er) { System.out.println(er.getMessage()); }
return novo;}
In this read function, I have one Compilation Warning: "…uses unchecked or unsafe operations. Recompile with - Xlint:unchecked for details."
To save:
public static void saveMyFile(String s, Object o)
{
try {
ObjectOutputStream oos = new ObjectOutputStream( new FileOutputStream(s));
oos.writeObject(o);
oos.flush();
oos.close();
}
catch(IOException e) { System.out.println(e.getMessage()); }
}
Finally, I want to print the ArrayList's info:
ArrayList<Equipa> cena = new ArrayList<Equipa>();
cena=(ArrayList<Equipa>) readMyFile("Equipas.dat");
for(Equipa e:cena)
e.toString();
Error when I try to run:
" writing aborted; java.io.NotSerializableException: Equipa"
Equipa havs the Serializable:
import java.util.*;
import java.io.*;
public class Equipa implements Serializable
{
private String nome;
private Carro carro;
private ArrayList<Piloto> pilotos;
private double tempoDecorrido;
private int pontos;
private boolean desistiu;
private int voltaDesistencia;
private Piloto piloto;
/**
* Constructor for objects of class Equipa
*/
public Equipa()
{
this.nome = "NA";
this.carro = null;
this.pilotos = new ArrayList<Piloto>();
this.tempoDecorrido = 0;
this.pontos = 0;
this.desistiu = false;
this.voltaDesistencia = 0;
this.piloto = null;
}
public Equipa(String nome, Carro carro, ArrayList<Piloto> pilotos)
{
this.nome = nome;
this.carro = carro;
//this.pilotos = new ArrayList<Piloto>(pilotos);
this.pilotos = pilotos;
this.tempoDecorrido = 0;
this.pontos = 0;
this.desistiu = false;
this.voltaDesistencia = 0;
//this.piloto = pilotos.get(0);
}
public Equipa (Equipa e)
{
this.nome = e.getNome();
this.carro = e.getCarro();
this.pilotos = e.getPilotos();
this.tempoDecorrido = e.getTempoDecorrido();
this.pontos = e.getPontos();
this.desistiu = e.getDesistiu();
this.voltaDesistencia = e.getVoltaDesistencia();
//this.piloto = e.getPiloto();
}
/** Getters */
public String getNome()
{
return this.nome;
}
public Carro getCarro()
{
return this.carro;
}
public ArrayList<Piloto> getPilotos()
{
return new ArrayList<Piloto>(this.pilotos);
}
public double getTempoDecorrido()
{
return this.tempoDecorrido;
}
public int getPontos()
{
return this.pontos;
}
public boolean getDesistiu()
{
return this.desistiu;
}
public int getVoltaDesistencia()
{
return this.voltaDesistencia;
}
public Piloto getPiloto()
{
return this.piloto;
}
/** Setters */
public void setNome(String nome)
{
this.nome = nome;
}
public void setCarro(Carro carro)
{
this.carro = carro;
}
public void setPilotos(ArrayList<Piloto> pilotos)
{
this.pilotos = new ArrayList<Piloto>(pilotos);
}
public void setTempoDecorrido(double tempoDecorrido)
{
this.tempoDecorrido = tempoDecorrido;
}
public void setPontos(int pontos)
{
this.pontos = pontos;
}
public void setDesistiu(boolean desistiu)
{
this.desistiu = desistiu;
}
public void setVoltaDesistencia(int voltaDesistencia)
{
this.voltaDesistencia = voltaDesistencia;
}
public void setPiloto(Piloto piloto)
{
this.piloto = piloto;
}
/** Outros Métodos */
public Equipa clone()
{
return new Equipa(this);
}
public boolean equals(Equipa e)
{
if(this.nome == e.getNome())
return true;
else
return false;
}
public String getStringPilotos()
{
String s = new String();
for(Piloto p: this.pilotos)
s = (s + ", " + p.getNome());
return s;
}
public String toString()
{
return new String("Nome da equipa: " + nome + "; Categoria do carro: " + carro.getClass().getName() + "; Marca e modelo: " + carro.getMarca() + " " + carro.getModelo() + "; Pilotos: " + getStringPilotos())+"\n";
}
Implementing Serializable means that serialization is permitted, but not necessarily that it is possible. For it to work, everything referenced by Equipa must also be either primitive or Serializable (and so on, recursively). Is this the case?
Warning in the read function is the result of generics in java. You won't be able to suppress it, unless you use #SuppressWarnings("unchecked") to ignore it.
If you are sure you are reading an ArrayList<Equipa>, you can ignore it without any problem.
With the Equipa code, I can try to point to the Serializable problem: make sure that Carro and Piloto classes are also Serializables. You can add the code of theses classes if you are not sure.
The only type-safer way would be do a custom serialization, using writeObject(OutputStream) and readObjectInputStream say on a class ArrayListOfEquipa maybe using Equipa[] (ArrayList.toArray()).
Not really attractive, if the warning would be the only reason.
Am really new to Java, started to study it on my own.... I downloaded netbeans and Eclipse and the two gave me the same result.. they don't run the code (stuck on running) neither let me debug it - Eclipse debugger and Netbeans - was not responding :? I don't whats wrong.. and I got no clue as I can't debug..
Here's my code: am tryin to check for palindrome:
package ClassQueue;
class Stack {
private Object[] Stack_Array = null;
public int top = 0;
public Stack(int size) {
top = 0;
Stack_Array = new Object[size];
}
public Stack() {
this(100);
}
protected void finalizer() {
Stack_Array = null;
}
final public boolean empty() {
return top == 0;
}
final public boolean full() {
return top == Stack_Array.length;
}
public void push(Object token) {
if (!full()) {
Stack_Array[top] = token;
top++;
}
}
public Object pop() {
Object Value_return = -999;
if (!empty()) {
Value_return = Stack_Array[top];
top--;
}
return Value_return;
}
}//end of Class_Stack
class Queue {
private Object[] Queue_Array = null;
private int Front = 0;
private int Rear = 0;
public Queue(int size) {
Front = Rear = 0;
Queue_Array = new Object[size];
}
public Queue() {
this(100);
}
protected void finalizer() {
Front = Rear = 0;
Queue_Array = null;
}
final public boolean empty() {
return Front == Rear;
}
final public boolean full() {
return Rear == Queue_Array.length;
}
public void queueAdd(Object token) {
if (!full()) {
Queue_Array[Rear] = token;
Rear++;
}
}
public Object queueDelete() {
Object Value_return = -999;
if (!empty()) {
Value_return = Queue_Array[Front];
Front++;
return Value_return;
}
return Value_return;
}
}//end of Class_Queue
public class ClassQueue {
public static void main(String[] args) {
int i = 0;
String Value_1 = "ABBA";
Stack Value_1_Stack = new Stack(Value_1.length());
Queue Value_1_Queue = new Queue(Value_1.length());
while (i < Value_1.length()) {
Value_1_Stack.push(Value_1.charAt(i));
Value_1_Queue.queueAdd(Value_1.charAt(i));
}
i = 0;
while (Value_1_Stack.pop() == Value_1_Queue.queueDelete()) {
i++;
}
if (i == Value_1.length()) {
System.out.println("Palindrome");
} else {
System.out.println("NOT");
}
}//end of main
}//end of ClassQueue
You've got an infinite loop here as i is never incremented:
while (i < Value_1.length()) {
Value_1_Stack.push(Value_1.charAt(i));
Value_1_Queue.queueAdd(Value_1.charAt(i));
}
Also don't exceed the length of the String Value_1:
while (i < Value_1.length() - 1) {
Value_1_Stack.push(Value_1.charAt(i));
Value_1_Queue.queueAdd(Value_1.charAt(i));
i++;
}
Aside: Use Java naming conventions for variable names.
You cannot create class with the name of package name.
To run your program
change the package name.
For ClassQueue create another ClassQueue.java file in same package.
To Debug program: Run>Debug
This will give you environment for debugging
Change view: Window>Show View>Debug