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
Related
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;
}
}
I'm writing program with several different algorithms for solving n-puzzle problem. I have problem with DFS algorithm, as it only finds solution for simplest combinations of depth 1 to 4, then it shows stack overflow error. Also, for depth 4 it shows solution of length 2147, which is obviously wrong. I ran out of ideas what is the problem.
I use HashMap to keep explored nodes and to retrace path. Here is my code for DFS:
public class DFS extends Path{
Node initial;
Node goal;
String order;
boolean isRandom = false;
ArrayList<Node> Visited = new ArrayList<Node>();
boolean goalFound=false;
public DFS(Node initial, String order, byte [][] goal_state){
this.initial=initial;
goal=new Node(goal_state);
this.order=order;
if(order.equals("Random"))isRandom=true;
Visited.add(initial);
path.put(this.initial, "");
runDFS(initial);
}
public void runDFS(Node current){
if(current.equals(goal))
{
goalFound=true;
System.out.println("Goal");
retracePath(current,true);
return;
}
if(!current.equals(goal) && goalFound==false)
{
Node child;
Moves m = new Moves(current);
if(isRandom)order=randomOrder("LRUD");
for (int i=0; i<4; i++)
{
String s = order.substring(i,i+1);
if(m.CanMove(s)==true)
{
child=m.move();
if(Visited.contains(child))
{
continue;
}
else
{
path.put(child,s);
Visited.add(child);
runDFS(child);
}
}
}
}
}
}
Node:
public class Node {
public byte[][] status;
private int pathcost;
public int getPathcost() {
return pathcost;
}
public void setPathcost(int pathcost) {
this.pathcost = pathcost;
}
public Node(byte[][] status)
{
this.status=new byte[status.length][status[0].length];
for(int i=0;i<status.length;i++){
for(int j=0;j<status[0].length;j++){
this.status[i][j]=status[i][j];
} }
}
#Override
public boolean equals(Object other)
{
if (!(other instanceof Node))
{
return false;
}
return Arrays.deepEquals(status, ((Node)other).status);
}
#Override
public int hashCode()
{
return Arrays.deepHashCode(status);
}
}
and Path:
public class Path {
public HashMap<Node,String> path;
public Path(){
path=new HashMap<Node, String>(100);
}
public void retracePath(Node nstate, boolean print){
String dir=path.get(nstate);
String textPath="";
int i=0;
while(!dir.equals("")){
textPath+=dir + ", ";
boolean changed=false;
if(dir.equals("L")) {dir="R"; changed=true;}
if(dir.equals("R") && changed==false) {dir="L";}
if(dir.equals("U")) {dir="D"; changed=true;}
if(dir.equals("D") && changed==false) {dir="U";}
Moves m=new Moves(nstate);
m.CanMove(dir);
nstate=new Node(m.move().status);
dir=path.get(nstate);
i++;
}
if(print==true) {textPath=textPath.substring(0,(textPath.length()-2));
System.out.println(i);
System.out.print(new StringBuffer(textPath).reverse().toString());}
}
public Node getParent(Node n){
String dir=path.get(n);
boolean changed=false;
if(dir.equals("L")) {dir="R"; changed=true;}
if(dir.equals("R") && changed==false) {dir="L";}
if(dir.equals("U")) {dir="D"; changed=true;}
if(dir.equals("D") && changed==false) {dir="U";}
Moves m=new Moves(n);
m.CanMove(dir);
n=new Node(m.move().status);
return n;
}
public String randomOrder(String order) {
ArrayList<Character> neworder = new ArrayList<Character>();
for(char c : order.toCharArray()) {
neworder.add(c);
}
Collections.shuffle(neworder);
StringBuilder newstring = new StringBuilder();
for(char c : neworder) {
newstring.append(c);
}
return newstring.toString();
}
}
If you have any ideas what is the problem and where is mistake I would be very thankful!
I'm trying to implement a linked list merge sort.
Here's the class I'm trying to do the merge sort in.
/**
* CS 200 Colorado State University, Fall 2011
*/
public class Member {
private String userID;
private String first;
private String last;
private EdgeStack edgeStack;
public void sortScore(Member member){
// calling a helper method
// this greedy method takes all the creds
edgeStack = sortEdgeStack(member);
}
private EdgeStack sortEdgeStack(Member member)
{
// our temp stacks
EdgeStack tempEdgeStack_A = new EdgeStack();
EdgeStack tempEdgeStack_B = new EdgeStack();
// our return value
EdgeStack result = null;
// storing the size of the stack
int sizeOfStack = member.getEdgeStack().getSize();
// base case
if(sizeOfStack<0){
return null;
}
// our true base case
else if(sizeOfStack==1)
{
// init stack
EdgeStack base = new EdgeStack();
base.push(member.getEdgeStack().pop());
return base;
}
else
{
// pop and store
for(int i = 0; i < (sizeOfStack / 2); i++)
{
tempEdgeStack_A.push(member.getEdgeStack().pop());
}
// pop and store into b
for(int j = (sizeOfStack/2)+1; j < sizeOfStack; j++)
{
tempEdgeStack_B.push(member.getEdgeStack().pop());
}
tempEdgeStack_A = sortEdgeStack(member);
tempEdgeStack_B = sortEdgeStack(member);
result = merge(tempEdgeStack_A,tempEdgeStack_B);
return result;
}
}
private EdgeStack merge(EdgeStack tempEdgeStack_A, EdgeStack tempEdgeStack_B) {
EdgeStack result = new EdgeStack();
// while either or
while(tempEdgeStack_A.getSize()> 0 || tempEdgeStack_B.getSize() > 0)
{
// if both are bigger then 0
if(tempEdgeStack_A.getSize()> 0 && tempEdgeStack_B.getSize() > 0)
{
if(tempEdgeStack_A.peek().getEdgeRank()<=tempEdgeStack_B.peek().getEdgeRank())
{
// adds b to result
result.push(tempEdgeStack_A.pop());
}
else
{
result.push(tempEdgeStack_B.pop());
}
}
// these elses cover if A or B are > 0 but A or B is also less then or equal too 0;
else if(tempEdgeStack_A.getSize()> 0)
{
while(tempEdgeStack_A.iterator().hasNext())
{
result.push(tempEdgeStack_A.iterator().next());
}
}
else if(tempEdgeStack_B.getSize()> 0)
{
while(tempEdgeStack_B.iterator().hasNext())
{
result.push(tempEdgeStack_B.iterator().next());
}
}
}
return result;
}
}
Here's the stack class (that implements a linked list). Why am I getting a stack overflow error?
import java.util.LinkedList;
import java.util.ListIterator;
/**
* CS 200 Colorado State University, Fall 2011
*/
public class EdgeStack {
private LinkedList<Edge> llist=new LinkedList<Edge>();
public EdgeStack(){
//add your code
}
public boolean isEmpty(){
return llist.isEmpty();
}
public void push(Edge e){
llist.add(e);
}
public Edge getIndexAt(int n){
return llist.get(n);
}
public Edge pop(){
return llist.remove();
}
public Edge peek(){
return llist.getLast();
}
public int getSize(){
return llist.size();
}
// public Edge peek(int n){
// LinkedList<Edge> temp=llist;
// return temp.peek();
// }
public LinkedList<Edge> popAll(){
LinkedList<Edge> temp=llist;
llist=null;
return temp; }
public ListIterator<Edge> iterator()
{
return llist.listIterator();
}
}
Check this:
else if(tempEdgeStack_A.getSize()> 0)
{
while(tempEdgeStack_A.iterator().hasNext())
{
result.push(tempEdgeStack_A.iterator().next());
}
}
else if(tempEdgeStack_B.getSize()> 0)
{
while(tempEdgeStack_B.iterator().hasNext())
{
result.push(tempEdgeStack_B.iterator().next());
}
}
You don't remove entries from the stacks, so the loop doesn't stop.
I would need some help with the following code if you are kind.
Basically i have a tree node that remembers it's parent node, depth-level and his current state(a 2D array).
Most variable names are written in my native language, i hope this is not a problem :
public class Nod implements Cloneable {
private Nod parinte;//parent node
private int[][] stare;//state
private int cost;//depth-level
private String actiune;//the action used to obtain this node
private volatile int hashCode = 0;
public boolean equals(Object obj)
{
if(this == obj)
{
return true;
}
if (!(obj instanceof Nod))
{
return false;
}
Nod nod = (Nod)obj;
return cost == nod.getCost() && actiune.equals(nod.getActiune())
&& stare.equals(nod.getStareNod());
}
public int hashCode()
{
StringBuffer strBuff = new StringBuffer();
try
{
int n = Problema.Dimensiune();//returns the dimension of state matrix
for (int i=0;i<n;i++)
for (int j=0;j<n;j++)
strBuff.append(stare[i][j]);
strBuff.append(cost);
strBuff.append(actiune);
String str = strBuff.toString();
hashCode = str.hashCode();
}
catch (IOException e) {
e.printStackTrace();
}
return hashCode;
}
public Object clone() throws CloneNotSupportedException
{
return super.clone();
}
public static boolean goUp(int[][] st) throws IOException
{
int n = Problema.Dimensiune();
boolean ok = false;
int[][] a = st;
for (int i=0;i<n;i++)
for (int j=0;j<n;j++)
{
if (a[i][j] == 0)
if (i != 0)
ok = true;
}
return ok;
}
public static boolean goDown(int[][] st) throws IOException
{
int n = Problema.Dimensiune();
boolean ok = false;
int[][] a = st;
for (int i=0;i<n;i++)
for (int j=0;j<n;j++)
{
if (a[i][j] == 0)
if (i != (n-1))
ok = true;
}
return ok;
}
public static boolean goLeft(int[][] st) throws IOException
{
int n = Problema.Dimensiune();
boolean ok = false;
int[][] a = st;
for (int i=0;i<n;i++)
for (int j=0;j<n;j++)
{
if (a[i][j] == 0)
if (j != 0)
ok = true;
}
return ok;
}
public static boolean goRight(int[][] st) throws IOException
{
int n = Problema.Dimensiune();
boolean ok = false;
int[][] a = st;
for (int i=0;i<n;i++)
for (int j=0;j<n;j++)
{
if (a[i][j] == 0)
if (j != (n-1))
ok = true;
}
return ok;
}
public static int[] Zero(int[][] st) throws IOException
{
int[][] a = st;
int n = Problema.Dimensiune();
int[] b = new int[2];
for (int i=0;i<n;i++)
for (int j=0;j<n;j++)
if (a[i][j] == 0)
{
b[0] = i;
b[1] = j;
}
return b;
}
public static int[][] Actiune(int[][] st, String s) throws IOException
{
int[][] a = st;
int[] b = Zero(st);
if ((goRight(st) == true) && (s == "right"))
{
a[b[0]][b[1]] = a[b[0]][b[1]+1];
a[b[0]][b[1]+1] = 0;
}
if ((goLeft(st) == true) && (s == "left"))
{
a[b[0]][b[1]] = a[b[0]][b[1]-1];
a[b[0]][b[1]-1] = 0;
}
if ((goUp(st) == true) && (s == "up"))
{
a[b[0]][b[1]] = a[b[0]-1][b[1]];
a[b[0]-1][b[1]] = 0;
}
if ((goDown(st) == true) && (s == "down"))
{
a[b[0]][b[1]] = a[b[0]+1][b[1]];
a[b[0]+1][b[1]] = 0;
}
return a;
}
public Nod(){}
public Nod (int[][] st)
{
parinte = null;
stare = st;
cost = 0;
actiune = null;
}
public Nod (Nod nod)
{
parinte = nod.parinte;
stare = nod.stare;
cost = nod.cost;
actiune = nod.actiune;
}
public Nod(Nod nodp, String ac) throws IOException
{
this.parinte = nodp;
this.cost = parinte.getCost()+1;
this.actiune = ac;
this.stare = Actiune(parinte.getStareNod(),actiune);
}
public void setCost(int cost)
{
this.cost = cost;
}
public int getCost(){
return this.cost;
}
public void setStareNod(int[][] stare)
{
this.stare = stare;
}
public int[][] getStareNod(){
return this.stare;
}
public void setNodParinte(Nod parinte)
{
this.parinte = parinte;
}
public Nod getNodParinte() throws IOException{
return this.parinte;
}
public void setActiune(String actiune)
{
this.actiune = actiune;
}
public String getActiune()
{
return this.actiune;
}
}
Now, i create an initial node and after, a child-node from it. The problem is that when i create the child-node, the parent's 2D array becomes identical with the child's array. I tried to clone the node object but it didn't fix it. I would appreciate if someone has an ideea how to fix it and shares it.
public class test {
public static void main(String[] args) throws IOException, CloneNotSupportedException
{
int[][] p = Problema.stareInitiala();
Nod nod = new Nod(p);
Nod nodc = (Nod) nod.clone();
Nod nod1 = new Nod(nodc,"right");
Nod nod1c = (Nod) nod1.clone();
Nod nod2 = new Nod(nod1c,"up");
if (nod.getStareNod().equals(nod.getStareNod()))
System.out.print("ok");
else
System.out.print("not ok");
}
}
So if p = {{7,2,4},{5,0,6},{8,3,1}} the if statement should return "not ok", but instead i get the "ok" message.
There is nothing broken or wrong about the clone mechanism. Just a bunch or programmers who don't understand it, here's a valid one for you class.
public Object clone() {
try {
Nod clone = (Nod)super.clone();
clone.stare = (int[][])stare.clone();
return clone;
} catch (CloneNotSupportedException cnse) {
//won't happen;
throw new RuntimeError("Won't happen");
}
}
This implementation assumes that the clone wants to use the same parent as the original. If this is not the case, you will need to clone that as well, or perhaps set the parent to null.
You may want to look at the documentation of the clone() method of Object. Default clone implementation (that is if you implemented Cloneable, which you did) performs shallow copy. This is probably not what you want, you may be better off by writing your own copying method.