The program that I am writing simulates a road charging system which reads several lines of inputs, each one representing a different command until I reach the EOF (\n).
This commands simulate a road charging system, where the input reads as follows:
PASS 44AB55 I -> where the first word is the command the program receives, the second word is the number plate of the car (44AB55) and the second is the status of the car (Regular or Irregular).
There are three types of commands:
“PASS 00AA00 R” – Increments the number of times that the car has passed in the system and marks its status has Regular or Irreguar. If the car isnt still in the database, it inserts the car as Regular and starts the counter with one passage.
“UNFLAG 00AA00” – Flags the car as Regular if it exists in the database. If the car doesnt exist in the database ignores the command.
“STATUS 00AA00” – Retrieves the status of the car (Regular or Irregular) and the number of passages of the car in the system. If it the car doesnt exist in the database, prints a "NO RECORD" message.
To solve this problem, I am using AVL trees and using the following code:
import java.util.ArrayList;
import java.util.Scanner;
public class TP2_probB {
static No raiz = null;
static double numRotacoes = 0;
static double numAtravessos = 0;
public static class No {
private String matricula;
private int porticos;
private boolean estadoRegular;
private No pai;
private No filhoEsq;
private No filhoDir;
private int balanco;
public No(String matricula, int porticos, boolean estadoRegular) {
this.matricula = matricula;
this.porticos = porticos;
this.estadoRegular = estadoRegular;
this.pai = null;
this.filhoDir = null;
this.filhoEsq = null;
this.balanco = 0;
}
public void setEstadoRegular(boolean estadoRegular) {
this.estadoRegular = estadoRegular;
}
public void setPai(No pai) {
this.pai = pai;
}
public void setFilhoEsq(No filhoEsq) {
this.filhoEsq = filhoEsq;
}
public void setFilhoDir(No filhoDir) {
this.filhoDir = filhoDir;
}
public void atribuiNoEsq(No noEsq) {
this.filhoEsq = noEsq;
}
public void atribuiNoDir(No noDir) {
this.filhoDir = noDir;
}
public void atribuiPai(No noPai) {
this.pai = noPai;
}
public void aumentaPortico() {
porticos++;
}
public String getMatricula() {
return matricula;
}
public boolean isEstadoRegular() {
return estadoRegular;
}
public No getPai() {
return pai;
}
public No getFilhoEsq() {
return filhoEsq;
}
public No getFilhoDir() {
return filhoDir;
}
#Override
public String toString() {
String estado;
if (estadoRegular == true) {
estado = "R";
} else {
estado = "I";
}
return matricula + " " + porticos + " " + estado;
}
}
public static No duplaRotacaoFilhoEsq(No k3)
{
k3.filhoEsq = rotacaoFilhoDir(k3);
return rotacaoFilhoEsq(k3);
}
public static No duplaRotacaoFilhoDir(No k3)
{
k3.filhoDir = rotacaoFilhoEsq(k3);
return rotacaoFilhoDir(k3);
}
public static No rotacaoFilhoDir(No k1) {
No k2 = k1.filhoDir;
k2.pai=k1.pai;
k1.filhoDir = k2.filhoEsq;
if(k1.filhoDir!=null)
{
k1.filhoDir.pai=k1;
}
k2.filhoEsq = k1;
k1.pai=k2;
if(k2.pai!=null)
{
if(k2.pai.filhoDir==k1)
{
k2.pai.filhoDir = k2;
}
else if(k2.pai.filhoEsq==k1)
{
k2.pai.filhoEsq = k2;
}
}
balanco(k2);
balanco(k1);
return k2;
}
public static No rotacaoFilhoEsq(No k1) {
No k2 = k1.filhoEsq;
k2.pai=k1.pai;
k1.filhoEsq = k2.filhoDir;
if(k1.filhoEsq!=null)
{
k1.filhoEsq.pai=k1;
}
k2.filhoDir = k1;
k1.pai=k2;
if(k2.pai!=null)
{
if(k2.pai.filhoDir==k1)
{
k2.pai.filhoDir = k2;
}
else if(k2.pai.filhoEsq==k1)
{
k2.pai.filhoEsq = k2;
}
}
balanco(k2);
balanco(k1);
return k2;
}
public static int pesagem(No aux)
{
if(aux==null)
{
return -1;
}
if(aux.filhoEsq == null && aux.filhoDir == null)
{
return 0;
}
else if ((aux.filhoEsq == null))
{
return (pesagem(aux.filhoDir) + 1);
}
else if ((aux.filhoDir == null))
{
return (pesagem(aux.filhoEsq) + 1);
}
else
return (Math.max(pesagem(aux.filhoEsq), pesagem(aux.filhoDir)) + 1);
}
public static void balanco(No tmp)
{
tmp.balanco = pesagem(tmp.filhoDir)-pesagem(tmp.filhoEsq);
}
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
String linha;
String[] aux;
ArrayList<String> output = new ArrayList<String>();
int x = 0;
while (true) {
linha = input.nextLine();
if (linha.isEmpty())
{
break;
}
else
{
aux = linha.split(" ");
if (aux[0].compareTo("PASS") == 0) {
No novo;
if (aux[2].compareTo("R") == 0) {
novo = new No(aux[1], 1, true);
} else {
novo = new No(aux[1], 1, false);
}
if (raiz == null) {
raiz = novo;
balanco(raiz);
} else {
procuraNo(novo);
}
} else if (aux[0].compareTo("UNFLAG") == 0) {
if (raiz != null) {
No no = new No(aux[1], 0, false);
mudaEstado(no);
}
} else if (aux[0].compareTo("STATUS") == 0) {
if (raiz == null) {
output.add(aux[1] + " NO RECORD");
} else {
No no = new No(aux[1], 0, false);
output.add(procuraRegisto(no));
}
}
}
}
for (int i = 0; i < output.size(); i++) {
System.out.println(output.get(i));
}
System.out.println("Número de Rotações: "+numRotacoes+"\nNúmero de atravessias: "+numAtravessos);
}
public static void procuraNo(No novo) {
No aux = raiz;
while (true) {
if (aux.getMatricula().compareTo(novo.getMatricula()) == 0) {
aux.aumentaPortico();
aux.setEstadoRegular(novo.isEstadoRegular());
equilibra(aux);
break;
} else if (aux.getMatricula().compareTo(novo.getMatricula()) < 0) {
if (aux.getFilhoDir() == null) {
novo.setPai(aux);
aux.setFilhoDir(novo);
aux=aux.filhoDir;
equilibra(aux);
break;
} else {
aux = aux.getFilhoDir();
numAtravessos++;
}
} else if (aux.getMatricula().compareTo(novo.getMatricula()) > 0) {
if (aux.getFilhoEsq() == null) {
novo.setPai(aux);
aux.setFilhoEsq(novo);
aux=aux.filhoEsq;
equilibra(aux);
break;
} else {
aux = aux.getFilhoEsq();
numAtravessos++;
}
}
}
}
public static void equilibra(No tmp) {
balanco(tmp);
int balanco = tmp.balanco;
System.out.println(balanco);
if(balanco==-2)
{
if(pesagem(tmp.filhoEsq.filhoEsq)>=pesagem(tmp.filhoEsq.filhoDir))
{
tmp = rotacaoFilhoEsq(tmp);
numRotacoes++;
System.out.println("Rodou");
}
else
{
tmp = duplaRotacaoFilhoDir(tmp);
numRotacoes++;
System.out.println("Rodou");
}
}
else if(balanco==2)
{
if(pesagem(tmp.filhoDir.filhoDir)>=pesagem(tmp.filhoDir.filhoEsq))
{
tmp = rotacaoFilhoDir(tmp);
numRotacoes++;
System.out.println("Rodou");
}
else
{
tmp = duplaRotacaoFilhoEsq(tmp);
numRotacoes++;
System.out.println("Rodou");
}
}
if(tmp.pai!=null)
{
equilibra(tmp.pai);
}
else
{
raiz = tmp;
}
}
public static void mudaEstado(No novo) {
No aux = raiz;
while (true) {
if (aux.getMatricula().compareTo(novo.getMatricula()) == 0) {
aux.setEstadoRegular(true);
break;
} else if (aux.getMatricula().compareTo(novo.getMatricula()) < 0) {
if (aux.getFilhoDir() == null) {
break;
} else {
aux = aux.getFilhoDir();
numAtravessos++;
}
} else if (aux.getMatricula().compareTo(novo.getMatricula()) > 0) {
if (aux.getFilhoEsq() == null) {
break;
} else {
aux = aux.getFilhoEsq();
numAtravessos++;
}
}
}
}
public static String procuraRegisto(No novo) {
No aux = raiz;
while (true) {
if (aux.getMatricula().compareTo(novo.getMatricula()) == 0) {
return aux.toString();
} else if (aux.getMatricula().compareTo(novo.getMatricula()) < 0) {
if (aux.getFilhoDir() == null) {
return (novo.getMatricula() + " NO RECORD");
} else {
aux = aux.getFilhoDir();
numAtravessos++;
}
} else if (aux.getMatricula().compareTo(novo.getMatricula()) > 0) {
if (aux.getFilhoEsq() == null) {
return (novo.getMatricula() + " NO RECORD");
} else {
aux = aux.getFilhoEsq();
numAtravessos++;
}
}
}
}
}
The problem is that I am getting a stack overflow error:
Exception in thread "main" java.lang.StackOverflowError
at TP2_probB.pesagem(TP2_probB.java:174)
at TP2_probB.pesagem(TP2_probB.java:177)
at TP2_probB.pesagem(TP2_probB.java:177)
at TP2_probB.pesagem(TP2_probB.java:177)
(...)
at TP2_probB.pesagem(TP2_probB.java:177)
Here is a link with two files with inputs used to test the program:
https://drive.google.com/folderview?id=0B3OUu_zQ9xlGfjZHRlp6QkRkREc3dU82QmpSSWNMRlBuTUJmWTN5Ny1LaDhDN3M2WkVjYVk&usp=sharing
Related
I am trying to get a binary search tree to balance.
I balance the tree after the insert method.
I hope someone here can guide me through this.
The method is balanceTheTree(...).
I did a recursive method, I don't know if it's the best solution
public class BinaryTreeTable<E extends Comparable<E>, T> implements Table<E, T> {
private Node root;
public BinaryTreeTable() {
this.root = new Node(null, null, null);
}
#Override
public boolean insert(E key, T data) {
boolean ret;
if (this.root.key == null) {
Node toInsert = new Node(null, key, data);
this.root = toInsert;
ret = true;
} else {
Node father = this.seekFather(key);
if (father == null) {
ret = false;
} else {
Node toInsert = new Node(father, key, data);
if (key.compareTo(father.key) > 0) {
father.rSon = toInsert;
ret = true;
balanceTheTree(toInsert);
} else if (key.compareTo(father.key) < 0) {
father.lSon = toInsert;
ret = true;
balanceTheTree(toInsert);
} else {
ret = false;
}
}
}
return ret;
}
private void rightRotation(Node theN) {
Node k2 = theN.rSon;
theN.rSon = k2.lSon;
k2.lSon = theN;
}
private void leftRotation(Node theN) {
Node k1 = theN.lSon;
theN.lSon = k1.rSon;
k1.rSon = theN;
}
private void leftRightRotation(Node theN) {
leftRotation(theN.rSon);
rightRotation(theN);
}
private void rightLeftRotation(Node theN) {
rightRotation(theN.lSon);
leftRotation(theN);
}
private void balanceTheTree(Node theN) {
if (theN == null) {
} else {
if (Math.abs(Math.subtractExact(computeH(theN.rSon), computeH(theN.lSon))) > 1) {
System.out.println("A droite " + theN.getLabel());
if (computeH(theN.lSon) > computeH(theN.rSon)) {
leftRotation(theN);
} else {
leftRightRotation(theN);
}
} else if (Math.abs(Math.subtractExact(computeH(theN.lSon), computeH(theN.rSon))) > 1) {
System.out.println("A gauche");
} else {
balanceTheTree(theN.rSon);
balanceTheTree(theN.lSon);
}
}
}
private int computeH(Node theN) {
int ret = 1;
if (theN == null) {
ret = 0;
} else if ((theN.lSon != null) && (theN.rSon == null)) {
ret = computeH(theN.lSon) + 1;
} else if ((theN.lSon == null) && (theN.rSon != null)) {
ret = computeH(theN.rSon) + 1;
} else if ((theN.lSon != null) && (theN.rSon != null)) {
ret = Math.max(computeH(theN.lSon), computeH(theN.rSon)) + 1;
}
return ret;
}
public class Node {
// Attributs
private Node lSon ;
private Node rSon ;
private Node father ;
private T theValue ;
private E key ;
// Constructeur
public Node (Node father, E key, T theValue) {
this.father = father;
this.key = key;
this.theValue = theValue;
}
public String getLabel() {
return String.valueOf(key);
}
public Node getLeft() {
return lSon;
}
public Node getRight() {
return rSon;
}
public Node clone() {
return new Node(this.father, this.key, this.theValue);
}
}
}
The computeH() method allows me to know the size of a node
The insertion method works correctly.
The tree i want to balance
public static void main(String[] args) {
BinaryTreeTable binaryTreeTable = new BinaryTreeTable();
binaryTreeTable.insert(10, "Test");
binaryTreeTable.insert(5, "Test");
binaryTreeTable.insert(7, "Test");
binaryTreeTable.insert(3, "Test");
binaryTreeTable.insert(4, "Test");
binaryTreeTable.insert(15, "Test");
binaryTreeTable.insert(19, "Test");
binaryTreeTable.insert(16, "Test");
binaryTreeTable.insert(20, "Test");
binaryTreeTable.showTree();
}
I'm working on an assignment where I have to solve a maze through backtracking (using a stack!) and the logic of the code is basically done, but the main problem is whenever I call pop() on my stack, it does not pop.So for now I have manually added (hardcoded) the parts in the maze where it is supposed to pop(). I am using my own stack that is using Linked Nodes and have ran JUnit and Main tests and it does indeed work (doubting myself here now). I have also used the Java stack and I get the same result.
Here is my code logic: As you can see in the method mazeSolver, at the bottom, I have a few if statements that check if i (operations performed) is at a certain point and it will "backtrack", but I am manually setting the position. The very last else statement is the part where I pop(). Any help would very much be appreciated.
public class MazeSolver {
private char[][] printMaze;
private char[][] solveMaze;
public MazeSolver() {
super();
}
private class Position {
private int x;
private int y;
Position(int y, int x) {
this.x = x;
this.y = y;
}
public int getX() {
return this.x;
}
public int getY() {
return this.y;
}
public void setX(int x) {
this.x = x;
}
public void setY(int y) {
this.y = y;
}
}
public boolean solve(boolean printUpdates) {
char space = ' ';
Stack<Position> stack = new Stack<Position>();
//Stack stack = new Stack();
Position cp = new Position(1, 0);
boolean done = true;
char c = 'C';
char x = 'X';
int i = 0;
while (done) {
// check right
if (printMaze[cp.getY()][cp.getX() + 1] == space && printMaze[cp.getY()][cp.getX() + 1] != x) {
cp.setX(cp.getX() + 1);
stack.push(cp);
printMaze[cp.getY()][cp.getX()] = 'C';
}
// check bottom
else if (printMaze[cp.getY() + 1][cp.getX()] == space && printMaze[cp.getY() + 1][cp.getX()] != x
&& printMaze[cp.getY() + 1][cp.getX()] != x) {
cp.setY(cp.getY() + 1);
stack.push(cp);
printMaze[cp.getY()][cp.getX()] = 'C';
}
// check top
else if (printMaze[cp.getY() - 1][cp.getX()] == space && printMaze[cp.getY() - 1][cp.getX()] != x) {
cp.setY(cp.getY() - 1);
stack.push(cp);
printMaze[cp.getY()][cp.getX()] = 'C';
}
// check left
else if (printMaze[cp.getY()][cp.getX() - 1] == space && printMaze[cp.getY()][cp.getX() - 1] != x) {
cp.setX(cp.getX() - 1);
stack.push(cp);
printMaze[cp.getY()][cp.getX()] = 'C';
}
//else {
/*
if (i == 6) {
printMaze[cp.getY()][cp.getX()] = 'X';
cp.setY(1);
cp.setX(5);
} else if (i == 27) {
printMaze[cp.getY()][cp.getX()] = 'X';
cp.setY(1);
cp.setX(20);
}
else if (i == 37) {
printMaze[cp.getY()][cp.getX()] = 'X';
cp.setY(2);
cp.setX(18);
}
else if (i == 68) {
printMaze[cp.getY()][cp.getX()] = 'X';
cp.setY(13);
cp.setX(22);
} else if (i == 69) {
printMaze[cp.getY()][cp.getX()] = 'X';
cp.setY(14);
cp.setX(22);
}
else if (i == 70) {
printMaze[cp.getY()][cp.getX()] = 'X';
cp.setY(15);
cp.setX(22);
} else if (i == 71) {
printMaze[cp.getY()][cp.getX()] = 'X';
cp.setY(16);
cp.setX(22);
} else if (i == 72) {
printMaze[cp.getY()][cp.getX()] = 'X';
cp.setY(17);
cp.setX(22);
} else if (i == 103) {
printMaze[cp.getY()][cp.getX()] = 'X';
cp.setY(21);
cp.setX(31);
} */else {
printMaze[cp.getY()][cp.getX()] = 'X';
stack.pop();
cp.setY(((Position) stack.top()).getY());
cp.setX(((Position) stack.top()).getX());
}
//}
i++;
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
// System.out.println(stack.top().getX() + ", " + stack.top().getY());
System.out.println(cp.getY() + ", " + cp.getX() + " i = " + i);
printMaze();
}
System.out.println("success");
return false;
}
public void printMaze() {
for (int i = 0; i < printMaze.length; i++) {
for (int j = 0; j < printMaze[i].length; j++) {
System.out.print(printMaze[i][j]);
}
System.out.println("");
}
}
public boolean loadMaze(String filename) {
BufferedReader br = null;
FileReader fr = null;
ArrayList<String> lines = new ArrayList<String>();
try {
fr = new FileReader(filename);
br = new BufferedReader(fr);
String line;
br = new BufferedReader(new FileReader(filename));
while ((line = br.readLine()) != null) {
lines.add(line);
}
printMaze = new char[lines.size()][];
solveMaze = new char[lines.size()][];
for (int i = 0; i < lines.size(); i++) {
printMaze[i] = new char[lines.get(i).length()];
solveMaze[i] = new char[lines.get(i).length()];
for (int j = 0; j < lines.get(i).length(); j++) {
solveMaze[i][j] = lines.get(i).charAt(j);
printMaze[i][j] = lines.get(i).charAt(j);
if (solveMaze[i][j] == 'S') {
// hint you need to do this but you do not have the
// instance variable yet
// start = new Position(i, j);
}
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)
br.close();
if (fr != null)
fr.close();
} catch (IOException ex) {
return false;
}
}
return true;
}
Here is my stack implementation if interested.
public class Stack<Item> implements StackInterface<Item> {
private int size;
private class Link {
private Item data;
public Link next;
public Link(Item data, Link next) {
this.data = data;
this.next = next;
}
public Item getData() {
return data;
}
}
private Link topStackLink = null;
public Stack() {
this.size = 0;
}
#Override
public void push(Item item) {
if (topStackLink == null) {
topStackLink = new Link(item, null);
} else {
topStackLink = new Link(item, topStackLink);
}
this.size++;
}
#Override
public void pop() {
// TODO Auto-generated method stub
if (topStackLink != null) {
topStackLink = topStackLink.next;
this.size--;
} else {
throw new java.util.EmptyStackException();
}
}
#Override
public Item top() {
if (topStackLink != null) {
return topStackLink.data;
} else {
throw new java.util.EmptyStackException();
}
}
#Override
public Item topAndPop() {
// TODO Auto-generated method stub
if (topStackLink != null) {
Item item = topStackLink.data;
pop();
return item;
} else {
throw new java.util.EmptyStackException();
}
}
#Override
public boolean isEmpty() {
if (topStackLink == null) {
return true;
} else {
return false;
}
}
#Override
public void makeEmpty() {
// TODO Auto-generated method stub
topStackLink = null;
this.size = 0;
}
#Override
public int size() {
return this.size;
}
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
Okey, I have no idea why I am getting this NullPointException. I have been trying for hours now, I AM GOING CRAZY!
Maybe some of u guys can help me. If u need more information, I will try to give it, just ask 4 it.
This is a link to a picture - CLICK ME! - NullPointerException
public class KjedetMengde<T> implements MengdeADT<T> {
private static Random rand = new Random();
private int antall; // antall elementer i mengden
private LinearNode<T> start;
/**
* Oppretter en tom mengde.
*/
public KjedetMengde() {
antall = 0;
start = null;
}//
#Override
public void leggTil(T element) {
if (!(inneholder(element))) {
LinearNode<T> node = new LinearNode<T>(element);
node.setNeste(start);
start = node;
antall++;
}
}
public void leggTilAlle(MengdeADT<T> m2) {
Iterator<T> teller = m2.oppramser();
while (teller.hasNext()) {
leggTil(teller.next());
}
}
#Override
public T fjernTilfeldig() {
LinearNode<T> forgjenger, aktuell;
T resultat = null;
if (!erTom()) {
int valg = rand.nextInt(antall) + 1;
if (valg == 1) {
resultat = start.getElement();
start = start.getNeste();
} else {
forgjenger = start;
for (int nr = 2; nr < valg; nr++) {
forgjenger = forgjenger.getNeste();
}
aktuell = forgjenger.getNeste();
resultat = aktuell.getElement();
forgjenger.setNeste(aktuell.getNeste());
}
antall--;
} // if
return resultat;
}//
#Override
public T fjern(T element) {
boolean funnet = false;
LinearNode<T> forgjenger = null;
LinearNode<T> aktuell = null;
T resultat = null;
if (!erTom()) {
if (start.getElement().equals(element)) {
resultat = start.getElement();
start = start.getNeste();
antall--;
} else {
forgjenger = start;
aktuell = start.getNeste();
for (int i = 1; i < antall && !funnet; i++) {
if (aktuell.getElement().equals(element)) {
funnet = true;
} else {
forgjenger = aktuell;
aktuell = aktuell.getNeste();
}
}
}
if (funnet) {
resultat = aktuell.getElement();
forgjenger.setNeste(aktuell.getNeste());
antall--;
}
}
return resultat;
}//
#Override
public MengdeADT<T> union(MengdeADT<T> m2) {// OBS! En bedre i kladdeopg4
KjedetMengde<T> begge = new KjedetMengde<T>();
LinearNode<T> aktuell = start;
while (aktuell != null) {
begge.leggTil(aktuell.getElement());
aktuell = aktuell.getNeste();
} // while
Iterator<T> teller = m2.oppramser();
while (teller.hasNext()) {
begge.leggTil(teller.next());
}
return begge;
}//
private void settInn(T element) {
LinearNode<T> nyNode = new LinearNode<T>(element);
nyNode.setNeste(start);
start = nyNode;
antall++;
}
#Override
public boolean inneholder(T element) {
boolean funnet = false;
LinearNode<T> aktuell = start;
for (int søk = 0; søk < antall && !funnet; søk++) {
if (aktuell.getElement().equals(element)) {
funnet = true;
} else {
aktuell = aktuell.getNeste();
}
}
return funnet;
}
#Override
public boolean erLik(MengdeADT<T> m2) {
boolean likeMengder = true;
T element = null;
if (antall() == m2.antall()) {
Iterator<T> teller = m2.oppramser();
while (teller.hasNext() && likeMengder) {
element = teller.next();
if (!this.inneholder(element)) {
likeMengder = false;
}
}
}
return likeMengder;
}
#Override
public boolean erTom() {
return antall == 0;
}
#Override
public int antall() {
return antall;
}
#Override
public Iterator<T> oppramser() {
return new KjedetIterator<T>(start);
}
#Override
public MengdeADT<T> snitt(MengdeADT<T> m2) {
KjedetMengde<T> kjede = new KjedetMengde<T>();
KjedetMengde<T> snitt = new KjedetMengde<T>();
LinearNode<T> aktuell = start;
while (aktuell != null) {
kjede.leggTil(aktuell.getElement());
aktuell = aktuell.getNeste();
}
Iterator<T> teller = m2.oppramser();
while (teller.hasNext()) {
T element = teller.next();
if (kjede.inneholder(element)) {
snitt.leggTil(element);
}
}
return snitt;
}
#Override
public MengdeADT<T> differans(MengdeADT<T> m2) { // (m1- m2)
KjedetMengde<T> kjede = new KjedetMengde<T>();
LinearNode<T> aktuell = start;
while (aktuell != null) {
kjede.leggTil(aktuell.getElement());
aktuell = aktuell.getNeste();
}
Iterator<T> teller = m2.oppramser();
while (teller.hasNext()) {
T element = teller.next();
if (kjede.inneholder(element)) {
kjede.fjern(element);
}
}
return kjede;
}
public String toString() {
String resultat = " ";
LinearNode<T> aktuell = start;
while (aktuell != null) {
resultat += aktuell.getElement().toString() + "\t";
aktuell = aktuell.getNeste();
}
return resultat;
}
}// class
public class Hobby {
private String hobbyNavn;
public Hobby (String hobby) {
hobbyNavn = hobby;
}
public String toString() {
return ("< " + hobbyNavn + " >");
}
public boolean equals (Object hobby2) {
Hobby hobbyDenAndre = (Hobby) hobby2;
return(hobbyNavn.equals(hobbyDenAndre.getHobbyNavn()));
}
public String getHobbyNavn() {
return hobbyNavn;
}
} //class
You are not initialising your hobbyer variable. You are even setting it to null in the constructor of Medlem.
Try
hobbyer = new KjedetMengde<Hobby>();
in either line 8 or 13 in your Medlem class.
I'm working on a program that will take a name and number of a periodic element, store it in a tree and then print it out in different orders.
When I try and run my main class it asks for the name, but then it doesn't go into the while loop.
Here is my main class.
public class BinarySearchTree
{
public static void main(String[] args)
{
Scanner conIn = new Scanner(System.in);
String name;
int atomicNum;
BSTInterface<PeriodicElement> elements = new BSTree<PeriodicElement>();
PeriodicElement element;
int numElements;
String skip;
System.out.print("Element name (press Enter to end): ");
name = conIn.nextLine();
while (!name.equals(""));
{
System.out.print("Atomic Number: ");
atomicNum = conIn.nextInt();
skip = conIn.nextLine();
element = new PeriodicElement(name, atomicNum);
elements.add(element);
System.out.print("Element name (press ENTER TO END): ");
name = conIn.nextLine();
}
System.out.println();
System.out.println("Periodic Elements");
numElements = elements.reset(BSTree.INORDER);
for (int count = 1; count <= numElements; count++)
{
System.out.println(elements.getNext(BSTree.INORDER));
}
}
}
Here is my Binary Search Tree
public class BSTree <T extends Comparable<T>>
implements BSTInterface<T>
{
protected BSTNode<T> root;
boolean found;
protected LinkedUnbndQueue<T> inOrderQueue;
protected LinkedUnbndQueue<T> preOrderQueue;
protected LinkedUnbndQueue<T> postOrderQueue;
public BSTree()
{
root = null;
}
public boolean isEmpty()
{
return (root == null);
}
private int recSize(BSTNode<T> tree)
{
if(tree == null)
{
return 0;
}
else
{
return recSize(tree.getLeft()) + recSize(tree.getRight()) + 1;
}
}
public int size()
{
int count = 0;
{
if(root != null)
{
LinkedStack<BSTNode<T>> hold = new LinkedStack<BSTNode<T>>();
BSTNode<T> currNode;
hold.push(root);
while(!hold.isEmpty())
{
currNode = hold.top();
hold.pop();
count++;
if(currNode.getLeft() != null)
{
hold.push(currNode.getLeft());
}
if(currNode.getRight() != null)
{
hold.push(currNode.getRight());
}
}
}
//System.out.println(count);
return count;
}
}
public boolean recContains(T element, BSTNode<T> tree)
{
if(tree == null)
{
return false;
}
else if(element.compareTo(tree.getInfo()) < 0)
{
return recContains(element, tree.getLeft());
}
else if(element.compareTo(tree.getInfo()) > 0)
{
return recContains(element, tree.getRight());
}
else
{
return true;
}
}
public boolean contains (T element)
{
//System.out.println("Tree contains: " + recContains(element, root));
return recContains(element, root);
}
public T recGet(T element, BSTNode<T> tree)
{
if(tree == null)
{
return null;
}
else if(element.compareTo(tree.getInfo()) < 0)
{
return recGet(element, tree.getLeft());
}
else if(element.compareTo(tree.getInfo()) > 0)
{
return recGet(element, tree.getRight());
}
else
{
return tree.getInfo();
}
}
public T get(T element)
{
//System.out.println(recGet(element, root));
return recGet(element, root);
}
public void add(T element)
{
root = recAdd(element, root);
}
private BSTNode<T> recAdd(T element, BSTNode<T> tree)
{
if(tree == null)
{
tree = new BSTNode<T>(element);
}
else if(element.compareTo(tree.getInfo()) <= 0)
{
tree.setLeft(recAdd(element, tree.getLeft()));
}
else
{
tree.setRight(recAdd(element, tree.getRight()));
}
return tree;
}
public boolean remove(T element)
{
root = recRemove(element, root);
return found;
}
private BSTNode<T> recRemove(T element, BSTNode<T> tree)
{
if(tree == null)
{
found = false;
}
else if (element.compareTo(tree.getInfo()) < 0)
{
tree.setLeft(recRemove(element, tree.getLeft()));
}
else if (element.compareTo(tree.getInfo()) > 0)
{
tree.setRight(recRemove(element, tree.getRight()));
}
else
{
tree = removeNode(tree);
found = true;
}
return tree;
}
private BSTNode<T> removeNode(BSTNode<T> tree)
{
T data;
if(tree.getLeft() == null)
{
return tree.getRight();
}
else if(tree.getRight() == null)
{
return tree.getLeft();
}
else
{
data = getPredecessor(tree.getLeft());
tree.setInfo(data);
tree.setLeft(recRemove(data, tree.getLeft()));
return tree;
}
}
private T getPredecessor(BSTNode<T> tree)
{
while (tree.getRight() != null)
{
tree = tree.getRight();
}
return tree.getInfo();
}
public int reset(int orderType)
{
int numNodes = size();
if(orderType == INORDER)
{
inOrderQueue = new LinkedUnbndQueue<T>(numNodes);
}
else
{
if(orderType == PREORDER)
{
preOrderQueue = new LinkedUnbndQueue<T>(numNodes);
preOrder(root);
}
if(orderType == POSTORDER)
{
postOrderQueue = new LinkedUnbndQueue<T>(numNodes);
postOrder(root);
}
}
return numNodes;
}
public T getNext(int orderType)
{
if(orderType == INORDER)
{
return inOrderQueue.dequeue();
}
else
{
if(orderType == PREORDER)
{
return preOrderQueue.dequeue();
}
else
{
if(orderType == POSTORDER)
{
return postOrderQueue.dequeue();
}
else
{
return null;
}
}
}
}
private void inOrder(BSTNode<T> tree)
{
if(tree != null)
{
inOrder(tree.getLeft());
inOrderQueue.enqueue(tree.getInfo());
inOrder(tree.getRight());
}
}
private void preOrder(BSTNode<T> tree)
{
if(tree != null)
{
preOrderQueue.enqueue(tree.getInfo());
preOrder(tree.getLeft());
preOrder(tree.getRight());
}
}
private void postOrder(BSTNode<T> tree)
{
if(tree != null)
{
postOrder(tree.getLeft());
postOrder(tree.getRight());
postOrderQueue.enqueue(tree.getInfo());
}
}
}
Here is the Binary Search Tree Node class
public class BSTNode <T extends Comparable<T>>
{
protected T info;
protected BSTNode<T> left;
protected BSTNode<T> right;
public BSTNode(T info)
{
this.info = info;
left = null;
right = null;
}
public void setInfo(T info)
{
this.info = info;
}
public T getInfo()
{
return info;
}
public void setLeft(BSTNode<T> link)
{
left = link;
}
public void setRight(BSTNode<T> link)
{
right = link;
}
public BSTNode<T> getLeft()
{
return left;
}
public BSTNode<T> getRight()
{
return right;
}
}
Remove the semi-colon that is terminating the while statement
while (!name.equals(""));
^
Remove the semi colon after the while statment because a semi colon makes it end there while a { is the start if while something is true or not (!) and it should end as you obviously know with a }.
In GXT is an example:
http://www.sencha.com/examples/#ExamplePlace:paginggrid
Where I can see realization of this method:
service.getPosts(loadConfig, callback);
or any other similar service
For example, here -
http://spring-rapid.googlecode.com/svn/trunk/atom-explorer/src/main/java/com/atom/ebank/wfront/examples/resources/server/ExampleServiceImpl.java
...
#Override
public PagingLoadResult<Post> getPosts(PagingLoadConfig config) {
if (posts == null) {
loadPosts();
}
if (config.getSortInfo().size() > 0) {
SortInfo sort = config.getSortInfo().get(0);
if (sort.getSortField() != null) {
final String sortField = sort.getSortField();
if (sortField != null) {
Collections.sort(posts, sort.getSortDir().comparator(new Comparator<Post>() {
public int compare(Post p1, Post p2) {
if (sortField.equals("forum")) {
return p1.getForum().compareTo(p2.getForum());
} else if (sortField.equals("username")) {
return p1.getUsername().compareTo(p2.getUsername());
} else if (sortField.equals("subject")) {
return p1.getSubject().compareTo(p2.getSubject());
} else if (sortField.equals("date")) {
return p1.getDate().compareTo(p2.getDate());
}
return 0;
}
}));
}
}
}
ArrayList<Post> sublist = new ArrayList<Post>();
int start = config.getOffset();
int limit = posts.size();
if (config.getLimit() > 0) {
limit = Math.min(start + config.getLimit(), limit);
}
for (int i = config.getOffset(); i < limit; i++) {
sublist.add(posts.get(i));
}
return new PagingLoadResultBean<Post>(sublist, posts.size(), config.getOffset());
}
...