NullPointerException - LinkedList [duplicate] - java

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.

Related

How to display all elements in a Prefix tree?

I'm trying to print all the word in my prefix tree. I can insert, it's working, but when I try to print all elements of the tree using a preorder way it just gets all messed up. There's some problem on the recursive method PREORDER that I'm using to display all elements.
How can I recursively display all the word on my prefix tree???
public class TrieMain {
public static void main(String[] args) {
TrieTree tree = new TrieTree();
tree.treeInsert("cat");
tree.treeInsert("cattle");
tree.treeInsert("hell");
tree.treeInsert("hello");
tree.treeInsert("rip");
tree.treeInsert("rap");
tree.preorder(tree.getRoot(), "");
}
}
public class TrieTree {
private TrieNode root;
private int wordCount;
public TrieTree() {
this.root = null;
this.wordCount = 0;
}
public TrieNode getRoot() {
return this.root;
}
public void setRoot(TrieNode newRoot) {
this.root = newRoot;
}
public int getWordCount() {
return this.wordCount;
}
public void preorder(TrieNode root, String prefix) {
if (root.getTerminal()) {
System.out.println(prefix);
}
for (int i = 0; i < 26; i++) {
if (root.getCharacters()[i] != '\u0000') {
prefix += root.getCharacters()[i];
preorder(root.getPointers()[i], prefix);
}
}
}
public boolean treeInsert(String word) {
if (this.root == null) {
this.root = new TrieNode();
}
TrieNode temp;
temp = this.root;
int lengthWord = word.length();
for (int i = 0; i < lengthWord; i++) {
int index = getIndex(word.charAt(i));
if (temp.getCharacters()[index] == '\u0000') {
temp.getCharacters()[index] = word.charAt(i);
temp.getPointers()[index] = new TrieNode();
}
temp = temp.getPointers()[index];
}
if (temp.getTerminal()) {
return false;
}
else {
temp.setTerminal(true);
return true;
}
}
public int getIndex(char character) {
int index = ((int) character) - 97;
return index;
}
}
public class TrieNode {
private final int NUM_CHARS = 26;
private char[] characters;
private TrieNode[] pointers;
private boolean terminal;
public TrieNode() {
this.characters = new char[this.NUM_CHARS];
this.pointers = new TrieNode[this.NUM_CHARS];
for (int i = 0; i < this.NUM_CHARS; i++) {
this.characters[i] = '\u0000';
this.pointers[i] = null;
}
this.terminal = false;
}
public char[] getCharacters() {
return this.characters;
}
public TrieNode[] getPointers() {
return this.pointers;
}
public boolean getTerminal() {
return this.terminal;
}
public void setTerminal(boolean newTerminal) {
this.terminal = newTerminal;
}
}

Java BinaryTree balance a tree

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

AVL tree in java

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

Why is my thread not ending?

Im pretty new to Java and to thread-programming especially. This code is mostly out of a pretty old book (2001) with samples and examples for a search-engine.
But its just not working
Now i don't know if i am making a mistake or if the author made it or if there are incompatibilities with different versions of java...i really have no clue! The oddest thing about it is that it works 1 out of 100 times ...
After hours of debugging i would appreciate any help!
SearchEngine.java:
import java.util.Vector;
import parsing.SourceElement;
import parsing.WebParserWrapper;
import query.Filter;
public class SearchEngine implements Runnable {
private Vector linkHistory = new Vector();
private int currentLink;
private String beginAt = null;
private SearchHandler searchHandler = null;
private boolean searchInProgress = false;
private boolean stopPending = false;
boolean firstTime = true;
public boolean searchInProgress() {
return searchInProgress;
}
public boolean stopPending() {
return stopPending;
}
#SuppressWarnings("unchecked")
public void followLinks(String url) {
if (stopPending)
return;
try {
boolean drillDown = false;
WebParserWrapper webParser = new WebParserWrapper();
Vector sortedElements = webParser.getElements(url, "", "WITHGET");
Vector contentElements = Filter.getFilteredElements(sortedElements, Filter.CONTENT, "matches", "*");
for (int i = 0; i < contentElements.size(); i++) {
SourceElement thisElement = (SourceElement) contentElements.elementAt(i);
String thisKey = (String) thisElement.getKey();
String thisContent = (String) thisElement.getContent();
boolean goodHit = searchHandler.handleElement(url, thisKey, thisContent);
if (goodHit) {
drillDown = true;
}
}
System.out.println(url + " -- DrillDown " + ((drillDown) ? "positive" : "negative"));
if (drillDown) {
Vector linkElements = Filter.getFilteredElements(sortedElements, Filter.KEY, "matches",
"*a[*].#href[*]");
for (int i = 0; i < linkElements.size(); i++) {
SourceElement thisElement = (SourceElement) linkElements.elementAt(i);
String thisContent = (String) thisElement.getContent();
if (!linkHistory.contains(thisContent)) {
linkHistory.add(thisContent);
System.out.println("Collected: " + thisContent);
}
}
}
}
catch (Exception e) {}
if (currentLink < linkHistory.size()) {
String nextLink = (String) linkHistory.elementAt(currentLink++);
if (nextLink != null) {
followLinks(nextLink);
}
}
}
public boolean startSearch(String url, SearchHandler searchHandler) {
if (searchInProgress)
return false;
beginAt = url;
this.searchHandler = searchHandler;
this.linkHistory = new Vector();
this.currentLink = 0;
Thread searchThread = new Thread(this);
searchThread.start();
return true;
}
public void stopSearch() {
stopPending = true;
}
#Override
public void run() {
searchInProgress = true;
followLinks(beginAt);
searchInProgress = false;
stopPending = false;
}
}
SimpleSearcher.java
import java.util.Enumeration;
import java.util.Hashtable;
public class SimpleSearcher implements SearchHandler {
private SearchEngine searchEngine;
private String keyword;
private String startURL;
private Hashtable hits = new Hashtable();
public boolean handleElement(String url, String key, String content) {
boolean goodHit = false;
int keywordCount = 0;
int pos = -1;
while ((pos = content.toLowerCase().indexOf(keyword, pos + 1)) >= 0){
keywordCount++;
}
if (keywordCount > 0) {
Integer count = (Integer) hits.get(url);
if (count == null){
hits.put(url, new Integer(1));
}
else {
hits.remove(url);
hits.put(url, new Integer(count.intValue() + keywordCount));
}
goodHit = true;
}
if (hits.size() >= 3)
searchEngine.stopSearch();
return goodHit;
}
public Hashtable search(String startURL, String keyword) {
searchEngine = new SearchEngine();
this.startURL = startURL;
this.keyword = keyword;
searchEngine.startSearch(startURL, this);
try {Thread.sleep(1000);}catch (Exception e){e.printStackTrace();}
while (searchEngine.searchInProgress());
return this.hits;
}
public static void main(String[] args) {
SimpleSearcher searcher = new SimpleSearcher();
String url = "http://www.nzz.ch/";
String compareWord = "der";
Hashtable hits = searcher.search(url, compareWord);
System.out.println("URLs=" + hits.size());
for (Enumeration keys = hits.keys(); keys.hasMoreElements();) {
String thisKey = (String) keys.nextElement();
int thisCount = ((Integer) hits.get(thisKey)).intValue();
System.out.println(thisCount + " hits at " + thisKey);
}
}
}
SearchHandler.java
public interface SearchHandler {
public boolean handleElement(String url, String key, String content);
}

NullPointerException from Canvas class(J2ME)

i'm having trouble from fetching data from my TimerCan class. like String and integers.
i have a method(static method) for getting this data and set it to another class. but every time i run my program i always get NULLPOINTEREXCEPTION in line..
if(opp.equalsIgnoreCase("incrementing")){///heree
startTimer();
if(hour[current]==hhh&&min[current]==mmm&&sec[current]==sss)
{
this.start = false;
this.stop = true;
this.timer.cancel();
}
else if(opp.equalsIgnoreCase("decrementing")){
startTimerD();
if(hour[current]==0&&min[current]==0&&sec[current]==0)
{
this.start = false;
this.stop = true;
this.timer.cancel();
and heres the full code my TimerCan class
public class TimerCan extends Canvas
{
private Timer timer;
private Midlet myMid;
private Player z;
private int hour[],sec[],min[],msec[],maxX,maxY,current,length,x,y;
private String time,opp;
private int strWid,hhh,mmm,sss;
private int strht;
private boolean start;
private boolean stop;
public Image img;
Data data;
public TimerCan(Midlet midlet)
{
this.myMid= midlet;
data = new Data();
opp=data.getData();
hhh=data.getDatah();
mmm=data.getDatam();
sss=data.getDatas();
try
{
this.maxX = this.getWidth();
this.maxY = this.getHeight();
this.current = 0;
this.hour = new int[30];
this.min = new int[30];
this.sec = new int[30];
this.msec = new int[30];
this.start = false;
this.stop = true;
for(int j = 0 ; j <= 30 ; j++)
{
this.hour[j] = 0;
this.min[j] = 0;
this.sec[j] = 0;
this.msec[j] = 0;
}
}catch(Exception e)
{}
}
public void paint(Graphics g)
{
Font font = Font.getFont(0,1,16);
this.strWid = font.stringWidth("this.time");
this.strht = font.getHeight();
if(hour[current] < 10)
{
time = "0"+String.valueOf(this.hour[current])+":";
}
else
{
time = String.valueOf(this.hour[current]) + ":";
}
if(min[current] < 10)
{
time = time+"0"+String.valueOf(this.min[current]) + ":";
}
else
{
time = time+String.valueOf(this.min[current]) + ":";
}
if(sec[current] < 10)
{
time = time+"0"+String.valueOf(this.sec[current]) + ":";
}
else
{
time = time + String.valueOf(this.sec[current]) + ":";
}
if(msec[current] < 10)
{
time = time+"0"+String.valueOf(this.msec[current]);
}
else
{
time = time+String.valueOf(this.msec[current]);
}
this.strWid = font.stringWidth(time);
this.length = this.maxX - this.strWid;
this.length /= 2;
try{
img = Image.createImage("/picture/aa.png");
}
catch(Exception error){
}
x = this.getWidth()/2;
y = this.getHeight()/2;
g.setColor(63,155,191);
g.fillRect(0,0,maxX, maxY);
g.drawImage(img, x, y, Graphics.VCENTER | Graphics.HCENTER);
g.setColor(0,0,0) ;
g.drawString(time,length+15,150,Graphics.TOP|Graphics.LEFT);
}
private void startTimer()
{
TimerTask task = new TimerTask()
{
public void run()
{
msec[current]++ ;
if(msec[current] == 100)
{
msec[current] = 0 ;
sec[current]++ ;
}
else if(sec[current] ==60)
{
sec[current] = 0 ;
min[current]++ ;
}
else if(min[current] == 60)
{
min[current] = 0 ;
hour[current]++ ;
}
else if(hour[current] == 24)
{
hour[current] = 0 ;
}
repaint();
}
};
timer = new Timer();
timer.scheduleAtFixedRate(task,10,10) ;
}
private void startTimerD()
{
TimerTask task = new TimerTask()
{
public void run()
{
msec[current]-- ;
if(msec[current] == 0)
{
msec[current] = 100 ;
sec[current]-- ;
}
else if(sec[current] ==0)
{
sec[current] = sss;
min[current]--;
}
else if(min[current] == 0)
{
min[current] =mmm;
hour[current]--;
}
else if(hour[current] == 0)
{
hour[current] = hhh;
}
repaint();
}
};
timer = new Timer();
timer.scheduleAtFixedRate(task,10,10) ;
}
protected void keyPressed(int keyCode)
{
if(keyCode == Canvas.KEY_NUM1)
{
if(this.start == false)
{
this.start=true;
this.stop=false;
}
else if(this.stop == false)
{
this.start = false ;
this.stop = true ;
this.timer.cancel();
}
if(start == true)
{
check();
}
}
if(keyCode == Canvas.KEY_NUM2)
{
this.min[current]=0;
this.sec[current]=0;
this.msec[current]=0;
this.start = false;
this.stop = true;
this.timer.cancel();
try{
z.deallocate();
}
catch(Exception e){}
repaint();
}
if(keyCode == Canvas.KEY_NUM3)
{
if(this.stop == false)
{
this.start = false;
this.stop = true;
this.timer.cancel();
try{
InputStream inss = getClass().getResourceAsStream("alarm.wav");
InputStreamReader iis= new InputStreamReader(inss);
z = Manager.createPlayer(inss,"audio/x-wav");
z.prefetch();
z.setLoopCount(2);
z.start();
}
catch(Exception e){
}
}
}
if(keyCode==Canvas.KEY_NUM0)
{
try{
z.deallocate();
}
catch(Exception e){}
myMid.exit();
}
}
public void check()
{
if(opp.equalsIgnoreCase("incrementing")){
startTimer();
if(hour[current]==hhh&&min[current]==mmm&&sec[current]==sss)
{
this.start = false;
this.stop = true;
this.timer.cancel();
try{
InputStream inss = getClass().getResourceAsStream("alarm.wav");
InputStreamReader iis= new InputStreamReader(inss);
z = Manager.createPlayer(inss,"audio/x-wav");
z.prefetch();
z.setLoopCount(2);
z.start();
}
catch(Exception e){
}
}
}
else if(opp.equalsIgnoreCase("decrementing")){
startTimerD();
if(hour[current]==0&&min[current]==0&&sec[current]==0)
{
this.start = false;
this.stop = true;
this.timer.cancel();
try{
InputStream inss = getClass().getResourceAsStream("alarm.wav");
InputStreamReader iis= new InputStreamReader(inss);
z = Manager.createPlayer(inss,"audio/x-wav");
z.prefetch();
z.setLoopCount(2);
z.start();
}
catch(Exception e){
}
}
and heres the Data classs
public class Data{
String nameD;
int hhD;
int mmD;
int ssD;
public void setData(String name){
this.nameD = name;
}
public String getData(){
return this.nameD;
}
//hour
public void setDatah(int hhh){
this.hhD = hhh;
}
public int getDatah(){
return this.hhD;
}
//
public void setDatam(int hhh){
this.mmD = hhh;
}
public int getDatam(){
return this.mmD;
}
//
public void setDatas(int sss){
this.ssD = sss;
}
public int getDatas(){
return this.ssD;
}
}
You wrote
data = new Data();
in your TimerCan class. This made a Data object that didn't have nameD set to anything; so when you wrote
opp = data.getData()
later, you were setting opp to null - that is, there wasn't actually an object referenced by opp. When you wrote
if (opp.equalsIgnoreCase("incrementing"))
this caused a problem. You can't call a method, when the object that you're trying to call it on is absent.
If it's legitimate for opp to be null, but you still have code that you want to run when opp is "incrementing" you can write it like this.
if (opp != null && opp.equalsIgnoreCase("incrementing"))
which will check whether opp is null before it calls the equalsIgnoreCase method - and you won't get the NullPointerException.
This happens because you have not initialized variable data, so it remains null. This is the obvious reason of NullPointerException.
You have to call data = new Data(); prior using it.

Categories