Whats wrong with this program? I want to stop all FutureTask immediately if one of them returns false as result. See line 100 and following. I've a list of future tasks. Then i instantiate an executor service and add all tasks. Then i execute the tasks and iterate through the task list, to check if one task returns false.
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.FutureTask;
public class PrimeIterator {
private boolean longBased = true;
private long startLong;
private BigInteger startBI;
public PrimeIterator(BigInteger start) {
if (start.compareTo(BigInteger.valueOf(Long.MAX_VALUE)) > 0) {
longBased = false;
}
if (longBased) {
startLong = start.longValue();
} else {
startBI = start;
}
}
public BigInteger nextPrime() {
BigInteger b;
while (true) {
if (longBased) {
if (isPrime(startLong)) {
b = BigInteger.valueOf(startLong);
increase();
return b;
}
} else {
if (isPrime(startBI)) {
b = startBI;
increase();
return b;
}
}
increase();
}
}
private boolean isPrime(long toTest) {
if (toTest % 2 == 0) {
return false;
}
long sqrt = (long) Math.sqrt(startLong);
for (long i = 3; i <= sqrt; i += 2) {
if (toTest % i == 0) {
return false;
}
}
return true;
}
private static class MyTask implements Callable<Boolean> {
private final BigInteger toTest;
private final BigInteger part;
private final int multiplier;
private static volatile boolean hasFalseResult;
private MyTask(BigInteger toTest, BigInteger part, int multiplier) {
this.toTest = toTest;
this.part = part;
this.multiplier = multiplier;
hasFalseResult = false;
}
#Override
public Boolean call() throws Exception {
BigInteger from = part.multiply(BigInteger.valueOf(multiplier)).add(BigInteger.valueOf(3));
BigInteger to = part.multiply(BigInteger.valueOf(multiplier + 1)).add(BigInteger.valueOf(3));
System.out.println("starting: " + toTest + " " + from + " " + to + " " + toTest.sqrt());
return isPrime(toTest, from, to);
}
private boolean isPrime(BigInteger b, BigInteger from, BigInteger to) {
for (BigInteger i = from; to.compareTo(i) > 0; i = i.add(BigInteger.TWO)) {
if (hasFalseResult) {
return false;
}
if (b.mod(i).compareTo(BigInteger.ZERO) == 0) {
hasFalseResult = true;
return false;
}
}
return true;
}
}
private boolean isPrime(BigInteger toTest) {
// if (toTest.isProbablePrime(5)) {
if (toTest.mod(BigInteger.TWO).compareTo(BigInteger.ZERO) == 0) {
return false;
}
BigInteger sqrt = toTest.sqrt();
BigInteger part = sqrt.divide(BigInteger.valueOf(10)).add(BigInteger.ONE);
List<FutureTask<Boolean>> taskList = new ArrayList<FutureTask<Boolean>>();
for (int i = 0; i < 10; i++) {
taskList.add(new FutureTask<>(new MyTask(toTest, part, i)));
}
ExecutorService executor = Executors.newFixedThreadPool(3);
for (FutureTask<Boolean> futureTask : taskList) {
executor.execute(futureTask);
}
try {
for (FutureTask<Boolean> futureTask : taskList) {
if (!futureTask.get()) {
return false;
}
}
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
return false;
}
return true;
// }
// return false;
}
private void increase() {
if (longBased) {
if (startLong == Long.MAX_VALUE) {
longBased = false;
startBI = BigInteger.valueOf(Long.MAX_VALUE).add(BigInteger.ONE);
} else {
startLong++;
}
} else {
startBI = startBI.add(BigInteger.ONE);
}
}
public static void main(String[] args) {
PrimeIterator pi = new PrimeIterator(BigInteger.valueOf(1));
for (int i = 0; i < 20; i++) {
System.out.println(pi.nextPrime());
}
pi = new PrimeIterator(BigInteger.valueOf(Long.MAX_VALUE - 10));
for (int i = 0; i < 5; i++) {
System.out.println(pi.nextPrime());
}
}
}
FutureTasks run in background threads. Once you return false, your isPrime() method will return immediately. But it won't stop other FutureTasks from completion as they are running in separate threads.
Related
I'm working on a simple(?) exercise for my Data Structures class. It works fine right up until I have an element leave the queue then try to add another one on at which point I get the following error:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 10 out of bounds for length 10
at queueExercise.IntegerQueue.join(IntegerQueue.java:20)
at queueExercise.IntegerQueueTest.main(IntegerQueueTest.java:27)
My code is as follows:
Queue Constructor Class:
public class IntegerQueue {
private int[] queue;
private int front;
private int end;
private int noInQueue;
private int count;
private boolean full;
public IntegerQueue(int max) {
queue = new int[max];
front = end = 0;
full = false;
}
public void join(int newValue) {
if (isFull()==false) {
queue[end] = newValue;
count++;
if (end == queue.length) {
end = 0;
}
else {
end++;
}
}else
System.out.println("Error: Queue Full");
}
public int leave() {
if (isEmpty()==false) {
noInQueue = queue[front];
queue[front]=0;
front++;
if (front==queue.length) {
front = 0;
}
count--;
}
else {
System.out.println("Error: Queue Empty");
}
System.out.println("Leaving: "+noInQueue);
return noInQueue;
}
public boolean isEmpty() {
if (count == 0){
return true;
}
else
return false;
}
public boolean isFull() {
if (count >= queue.length) {
return true;
}
else
return false;
}
public void printQueue() {
if (!isEmpty()) {
System.out.println("Printing Queue");
int pos = front;
int i =0;
while(i<queue.length) {
System.out.println(queue[pos]);
pos++;
i++;
if (pos >=queue.length) {
pos = 0;
}
}
}
}
}
Test Class
public class IntegerQueueTest {
static IntegerQueue q = new IntegerQueue(10);
public static void main(String[] args) {
int j;
System.out.println("Creating Queue");
for (int i = 0; i <10; i++) {
j = (int)(Math.random()*100);
if (!q.isFull()) {
q.join(j);
System.out.println("Adding: "+j);
}
}
q.printQueue();
q.join(112);
q.leave();
q.leave();
q.leave();
q.printQueue();
q.join(112);
q.join(254);
q.printQueue();
}
}
The problem is in the join method and more precisely in the condition if (end == queue.length). All you have to do is change it to if (end == queue.length - 1).
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
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);
}
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.
The objective is to count distinct words from a file.
UPDATE: Previous Code was successfully finished. Now I have to do the same but using threads (Oh man, I hate them...) and in addition I want to make it with semaphores for better flow.
Code contains some extra stuff left out from previous attempts, I'm trying to figure out what can be used..
I can read one word at a time but mostly I get a "null" in the container. So until I get anything from the container all the time I can't test the Sorter class and so on...
The new addition to the program is WordContainer class to store one word to pass it from reader to sorter:
package main2;
import java.util.ArrayList;
public class WordContainer
{
private ArrayList<String> words;
public synchronized String take()
{
String nextWord = null;
while (words.isEmpty())
{
try
{
wait();
}
catch (InterruptedException e)
{
}
}
nextWord = words.remove(0);
notify();
return nextWord;
}
public synchronized void put(String word)
{
while (words.size() > 999)
{
try
{
wait();
}
catch (InterruptedException e)
{
}
}
words.add(word);
notify();
}
}
DataSet Class combined with Sorter method resulting in Sorter Class:
package main2;
import java.util.concurrent.Semaphore;
public class Sorter extends Thread
{
private WordContainer wordContainer;
private int top;
private String[] elements;
private boolean stopped;
private Semaphore s;
private Semaphore s2;
public Sorter(WordContainer wordContainer, Semaphore s, Semaphore s2)
{
this.wordContainer = wordContainer;
elements = new String[1];
top = 0;
stopped = false;
this.s = s;
this.s2 = s2;
}
public void run()
{
String nextWord = wordContainer.take();
while (nextWord != null)
{
try
{
s.acquire();
}
catch (InterruptedException e)
{
e.printStackTrace();
}
nextWord = wordContainer.take();
s2.release();
add(nextWord);
}
}
public void startSorting()
{
start();
}
public void stopSorting()
{
stopped = true;
}
public boolean member(String target)
{
if (top > 0)
{
return binarySearch(target, 0, top);
}
else
{
return false;
}
}
private boolean binarySearch(String target, int from, int to)
{
if (from == to - 1)
{
return elements[from].equals(target);
}
int middle = (to - from) / 2 + from;
if (elements[from].equals(target))
{
return true;
}
if (elements[middle].compareTo(target) > 0)
{
// search left
return binarySearch(target, from, middle);
}
else
{
// search right
return binarySearch(target, middle, to);
}
}
public void add(String nextElement)
{
if (top < elements.length)
{
elements[top++] = nextElement;
System.out.println("[" + top + "] " + nextElement);
sort();
}
else
{
String[] newArray = new String[elements.length * 2];
for (int i = 0; i < elements.length; i++)
{
newArray[i] = elements[i];
}
elements = newArray;
add(nextElement);
}
}
private void sort()
{
int index = 0;
while (index < top - 1)
{
if (elements[index].compareTo(elements[index + 1]) < 0)
{
index++;
}
else
{
String temp = elements[index];
elements[index] = elements[index + 1];
elements[index + 1] = temp;
if (index > 0)
{
index--;
}
}
}
}
public int size()
{
return top;
}
public String getSortedWords()
{
String w = "";
for (int i = 0; i < elements.length; i++)
{
w += elements[i] + ", ";
}
return w;
}
public int getNumberOfDistinctWords()
{
return top;
}
}
Reader Class now looks like this:
package main2;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.concurrent.Semaphore;
public class Reader extends Thread
{
private static final int whitespace = 45;
private static final int word = 48;
private static final int finished = -1;
private WordContainer wordContainer;
private Semaphore s;
private Semaphore s2;
private String[] wordsR;
private int state;
private BufferedReader reader;
private int nextFreeIndex;
public Reader(File words, WordContainer wordContainer, Semaphore s,
Semaphore s2)
{
state = whitespace;
try
{
reader = new BufferedReader(new FileReader(words));
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
nextFreeIndex = 0;
wordsR = new String[1];
this.wordContainer = wordContainer;
this.s = s;
this.s2 = s;
}
public void startReading()
{
start();
}
public void run()
{
String nextWord = readNext();
while (nextWord != null)
{
nextWord = readNext();
wordContainer.put(nextWord);
s.release();
try
{
s2.acquire();
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
public String readNext()
{
int next;
StringBuffer nextWord = new StringBuffer();
while (true)
{
try
{
next = reader.read();
}
catch (IOException e)
{
next = -1;
}
char nextChar = (char) next;
switch (state)
{
case whitespace:
if (isWhiteSpace(nextChar))
{
state = whitespace;
}
else if (next == -1)
{
state = finished;
}
else
{
nextWord.append(nextChar);
state = word;
}
break;
case word:
if (isWhiteSpace(nextChar))
{
state = whitespace;
return nextWord.toString();
}
else if (next == -1)
{
state = finished;
return nextWord.toString();
}
else
{
nextWord.append(nextChar);
state = word;
}
break;
case finished:
return null;
}
}
}
private boolean isWhiteSpace(char nextChar)
{
switch (nextChar)
{
case '-':
case '"':
case ':':
case '\'':
case ')':
case '(':
case '!':
case ']':
case '?':
case '.':
case ',':
case ';':
case '[':
case ' ':
case '\t':
case '\n':
case '\r':
return true;
}
return false;
}
public void close()
{
try
{
reader.close();
}
catch (IOException e)
{
}
}
public String getWords()
{
return wordContainer.take();
}
}
Test Class
package test;
import java.io.File;
import java.io.IOException;
import java.util.concurrent.Semaphore;
import main2.Reader;
import main2.Sorter;
import main2.WordContainer;
import junit.framework.Assert;
import junit.framework.TestCase;
public class TestDistinctWordsWithThreads extends TestCase
{
public void test() throws IOException, InterruptedException
{
File words = new File("resources" + File.separator + "AV1611Bible.txt");
if (!words.exists())
{
System.out.println("File [" + words.getAbsolutePath()
+ "] does not exist");
Assert.fail();
}
WordContainer container = new WordContainer();
Semaphore s = new Semaphore(0);
Semaphore s2 = new Semaphore(0);
Reader reader = new Reader(words, container, s, s2);
Sorter sorter = new Sorter(container, s, s2);
reader.startReading();
sorter.startSorting();
reader.join();
sorter.join();
System.out.println(reader.getWords());
Assert.assertTrue(sorter.getNumberOfDistinctWords() == 14720);
/*
* String bible = reader.getWords(); System.out.println(bible); String[]
* bible2 = sorter.getSortedWords(); System.out.println(bible2);
* assertTrue(bible2.length < bible.length());
*/
}
}
Why don't you sinply try something like:
public int countWords(File file) {
Scanner sc = new Scanner(file);
Set<String> allWords = new HashSet<String>();
while(sc.hasNext()) {
allWords.add(sc.next());
}
return allWords.size();
}