I'm writing a test program currently to check for points within a circle. But the method to check if the point is in the circle isn't invoked. Did I do something? Can someone kindly advise on how to solve this issue?
btSearch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
rad = spRadius.getSelectedItem().toString();
if (rad.equals("1km")) {
circle.setRadius(500);
processJSON();
} else if (rad.equals("100m")) {
circle.setRadius(50);
processJSON();
} else if (rad.equals("500m")) {
circle.setRadius(250);
processJSON();
}
}
private void processJSON() {
try {
if (mJSONObject != null) {
Iterator<String> keys = mJSONObject.keys();
while (keys.hasNext()) {
String key = keys.next();
JSONObject jsonObj = mJSONObject.getJSONObject(key);
String point = jsonObj.getString("coords");
String[] latlong = point.split(",");
latpoint = Double.parseDouble(latlong[0]);
lngpoint = Double.parseDouble(latlong[1]);
Toast.makeText(this,latpoint+"+"+lngpoint,Toast.LENGTH_SHORT).show();
if (checkPointInCircle(latcenter, lngcenter, latpoint, lngpoint)) {
mMap.addMarker(new MarkerOptions().
position(new LatLng(latpoint, lngpoint)).title("busstop"));
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
public boolean checkPointInCircle(double latcenter, double lngcenter, double latpoint, double lngpoint) {
Double radi = Double.parseDouble(rad);
double latdiff = (latpoint - latcenter);
latdiff = Math.pow(latdiff, 2);
double longdiff = (lngpoint - lngcenter);
longdiff = Math.pow(longdiff, 2);
radi = Math.pow(radi, 2);
if (latdiff + longdiff < radi) {
return true;
}
return false;
}
Related
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;
}
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
I have code to stored the value using RMS in J2ME. It's working fine on emulator. So, my first problem is
When i restart the emulator all the stored values are deleted.
Stored values are showing in the emulator, but not in the Mobile, in which i am testing my application.
I am using NetBeans for developing my J2ME application.
===UPDATED===
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;
import javax.microedition.rms.*;
public class TryNew extends MIDlet implements CommandListener, ItemCommandListener {
private RecordStore record;
private StringItem registered;
static final String REC_STORE = "SORT";
//Button existUser;
Display display = null;
private Ticker ticker;
Form form = null;
Form form1 = null;
TextField tb, tb1, tb2, tb3;
ChoiceGroup operator = null;
String str = null;
Command backCommand = new Command("Back", Command.BACK, 0);
Command loginCommand = new Command("Login", Command.OK, 2);
Command saveCommand = new Command("Save New", Command.OK, 1);
Command sendCommand = new Command("Send", Command.OK, 2);
Command selectCommand = new Command("Select", Command.OK, 0);
Command exitCommand = new Command("Exit", Command.STOP, 3);
private ValidateLogin ValidateLogin;
public TryNew() {
}
public void startApp() throws MIDletStateChangeException {
display = Display.getDisplay(this);
form = new Form("Login");
registered = new StringItem("", "Registered ?", StringItem.BUTTON);
form1 = new Form("Home");
tb = new TextField("Login Id: ", "", 10, TextField.PHONENUMBER);//TextField.PHONENUMBER
tb1 = new TextField("Password: ", "", 30, TextField.PASSWORD);
operator = new ChoiceGroup("Select Website", Choice.POPUP, new String[]{"Game", "Joke", "SMS"}, null);
form.append(tb);
form.append(tb1);
form.append(operator);
form.append(registered);
registered.setDefaultCommand(selectCommand);
registered.setItemCommandListener(this);
form.addCommand(saveCommand);
ticker = new Ticker("Welcome Screen");
form.addCommand(loginCommand);
form.addCommand(selectCommand);
form.addCommand(exitCommand);
// existUser = new StringItem(null, "Registered ?");
// form.append(existUser);
form.setCommandListener(this);
form1.addCommand(exitCommand);
form1.addCommand(sendCommand);
form1.setCommandListener(this);
form.setTicker(ticker);
display.setCurrent(form);
}
public void pauseApp() {
}
public void destroyApp(boolean unconditional) {
}
void showMessage(String message, Displayable displayable) {
Alert alert = new Alert("");
alert.setTitle("Error");
alert.setString(message);
alert.setType(AlertType.ERROR);
alert.setTimeout(5000);
display.setCurrent(alert, displayable);
}
public void commandAction(Command c, Displayable d) {
if (c == exitCommand) {
destroyApp(true);
notifyDestroyed();
} else if (c == backCommand) {
display.setCurrent(form);
} else if (c == loginCommand) {
ValidateLogin = new ValidateLogin(this);
ValidateLogin.start();
ValidateLogin.validateLogin(tb.getString(), tb1.getString(), operator.getString(operator.getSelectedIndex()));
} else if (c == saveCommand) {
openRecord();
writeRecord(tb.getString(), tb1.getString(), operator.getString(operator.getSelectedIndex()));
closeRecord();
showAlert("Login Credential Saved Successfully !!");
}
}
////==============================================================================/////
/// Record Management
public void openRecord() {
try {
record = RecordStore.openRecordStore(REC_STORE, true);
} catch (Exception e) {
db(e.toString());
}
}
public void closeRecord() {
try {
record.closeRecordStore();
} catch (Exception e) {
db(e.toString());
}
}
public void deleteRecord() {
if (RecordStore.listRecordStores() != null) {
try {
RecordStore.deleteRecordStore(REC_STORE);
} catch (Exception e) {
db(e.toString());
}
}
}
public void writeRecord(String login_id, String pwd, String operator_name) {
String credential = login_id + "," + pwd + "," + operator_name;
byte[] rec = credential.getBytes();
try {
if (login_id.length() > 10 || login_id.length() < 10) {
showAlert("Please Enter valid Login Id");
} else if (pwd.length() < 1) {
showAlert("Please Password !!");
} else {
record.addRecord(rec, 0, rec.length);
}
} catch (Exception e) {
db(e.toString());
}
}
private void showAlert(String err) {
Alert a = new Alert("");
a.setString(err);
a.setTimeout(Alert.FOREVER);
display.setCurrent(a);
}
public void readRecord() {
try {
if (record.getNumRecords() > 0) {
Comparator comp = new Comparator();
RecordEnumeration re = record.enumerateRecords(null, comp, false);
while (re.hasNextElement()) {
String str = new String(re.nextRecord());
showAlert(str);
}
}
} catch (Exception e) {
db(e.toString());
}
}
private void db(String error) {
System.err.println("Exception: " + error);
}
public void commandAction(Command c, Item item) {
if (c == selectCommand && item == registered) {
openRecord();
readRecord();
closeRecord();
}
}
class Comparator implements RecordComparator {
public int compare(byte[] rec1, byte[] rec2) {
String str1 = new String(rec1);
String str2 = new String(rec2);
int result = str1.compareTo(str2);
if (result == 0) {
return RecordComparator.EQUIVALENT;
} else if (result < 0) {
return RecordComparator.PRECEDES;
} else {
return RecordComparator.FOLLOWS;
}
}
}
class ValidateLogin implements Runnable {
TryNew midlet;
private Display display;
String login_id;
String pwd;
String operator_name;
public ValidateLogin(TryNew midlet) {
this.midlet = midlet;
display = Display.getDisplay(midlet);
}
public void start() {
Thread t = new Thread(this);
t.start();
}
public void run() {
if (login_id.length() > 10 || login_id.length() < 10) {
showAlert("Please Enter valid Login Id");
} else if (pwd.length() < 1) {
showAlert("Please Password !!");
} else {
showHome();
}
}
/* This method takes input from user like text and pass
to servlet */
public void validateLogin(String login_id, String pwd, String operator_name) {
this.login_id = login_id;
this.pwd = pwd;
this.operator_name = operator_name;
}
/* Display Error On screen*/
private void showAlert(String err) {
Alert a = new Alert("");
a.setString(err);
a.setTimeout(Alert.FOREVER);
display.setCurrent(a);
}
private void showHome() {
tb2 = new TextField("To: ", "", 30, TextField.PHONENUMBER);
tb3 = new TextField("Message: ", "", 300, TextField.ANY);
form1.append(tb2);
form1.append(tb3);
form1.addCommand(loginCommand);
//display.setCurrent(tb3);
display.setCurrent(form1);
}
};
}
This is what i got, when i click the Manage Emulator
You need to fix the storage_root of your app in WTK,
Whenever you start your enulator it would refer to same storage_root, by default it creates different data files for each session
Follow-up on a previous question I posted about a combat simulator.
The problem here: 'Creature' objects do not enter the stack on the 'Combat' class.
The whole thing is several classes larger but I've managed to narrow the problem to the following code.
public class Combat implements Runnable {
int Turn = 0;
HashMap<Integer, Faction> Factions = new HashMap<Integer, Faction>();
Stack<Creature> stack;
public int getFactionsStanding() {
int Result = 0;
Iterator<Faction> F = Factions.values().iterator();
while(F.hasNext()) {
if (F.next().getMemberCount() > 0)
Result = Result + 1;
}
return Result;
}
public HashMap<Integer, Creature> getEnemies(int factionID) throws NoFactionsException {
HashMap<Integer, Creature> targetPool = new HashMap<Integer, Creature>();
Iterator<Faction> F = Factions.values().iterator();
if (!(F.hasNext()))
throw new NoFactionsException();
Faction tempFaction;
while (F.hasNext()){
tempFaction = F.next();
if (tempFaction.getfactionID() != factionID)
targetPool.putAll(tempFaction.getMembers());
}
return targetPool;
}
private int getMaxInit(){
int Max = 0, temp = 0;
Iterator<Faction> I = Factions.values().iterator();
while(I.hasNext()){
temp = I.next().getMaxInit();
if (temp > Max)
Max = temp;
}
return Max;
}
public int getTurn() {
return Turn;
}
public void setTurn(int turn) {
Turn = turn;
}
// TODO I can't get creatures to enter the stack! :#
synchronized public void push(Creature C){
stack.push(C);
System.out.println("Creature " + C.getName() + " is now on the stack");
if (C.getInit() == this.getMaxInit())
this.emptyStack();
notify();
}
// TODO The stack must be processed now: everyone does what they intended to do
public void emptyStack(){
Creature C;
while (!(stack.isEmpty())){
C = stack.pop();
C.takeAction();
}
Turn = 0;
}
synchronized public void increaseTurn(){
this.Turn = Turn + 1;
System.out.println("Current initiative score is " + this.getTurn());
notifyAll();
try {
Thread.sleep(100);
} catch (InterruptedException e) {
return;
}
}
public void run(){
while(this.getFactionsStanding() > 1){
increaseTurn();
}
}
}
public class Creature extends Observable implements Runnable {
synchronized public void declareAction(){
try{
if (Combat.getTurn() != this.getInit())
wait();
Combat.push(this);
}
catch (InterruptedException e){
return;
}
}
public void takeAction(){
Attack(this.Target, this.leftHandWeapon);
if (this.Target.getCurrentHP() < 0)
this.Target = null;
}
public void setTarget() {
Integer targetID = -1;
HashMap<Integer, Creature> targetPool;
Object[] targetKeys;
try{
targetPool = Combat.getEnemies(FID);
if (targetPool.isEmpty())
throw new EmptyTargetPoolException();
targetKeys = targetPool.keySet().toArray();
if (targetKeys.length == 0)
throw new EmptyTargetKeysArrayException();
if (this.Target == null) {
do{
targetID = (Integer) this.getRandom(targetKeys); //(Integer)targetKeys[(Integer) this.getRandom(targetKeys)];
} while (!(targetPool.keySet().contains((Integer)targetID)));
this.Target = targetPool.get(targetID);
}
}
catch (EmptyTargetPoolException e) {
System.out.println(e.getMessage());
}
catch (EmptyTargetKeysArrayException e) {
System.out.println(e.getMessage());
}
catch (Exception e) {
System.out.println(e.getMessage());
}
}
public void run() {
// This will go on and on as long as this creature is alive
while (this.currentHP > 0) {
try {
this.setInit();
this.setTarget();
this.declareAction();
}
catch (Exception e){
System.out.println(e.getMessage());
}
}
System.out.println(this.Name + " was killed!");
}
}
Does the creatures name get printed out? If so there may be a problem with:
if (C.getInit() == this.getMaxInit())
this.emptyStack();
I'm not sure what the method getInit() does but if getMaxInit() also returns the same value then it could just empty the stack each time push() is called. Its the only problem I can see right now that could happen.
Did anyone see Suggest or AutoComplete TextArea GWT Widget? It doesn't have to be completely the same as SuggestBox. I'm just wondering about something being out there already before I dive into developing it myself.
There is a GWT library here there is also a demo here
You also might want to check out the multi-value auto-completer from Spiffy UI. This is a newer version of the auto-completer mentioned by z00bs and part of this reusable framework.
http://www.zackgrossbart.com/hackito/gwt-rest-auto/ might be what you're looking for.
A long time ago in a project far, far away, i wrote the class that could be helpful:
public class SuggestTextArea extends TextArea {
private SuggestingPopupPanel suggestingPanel;
private SuggestTextArea textArea = this;
public SuggestTextArea(List<String> keywords) {
super();
suggestingPanel = new SuggestingPopupPanel(keywords, "suggestion");
this.getElement().setAttribute("spellcheck", "false");
this.addKeyPressHandler(new KeyPressHandler() {
public void onKeyPress(KeyPressEvent event) {
int charCode = event.getNativeEvent().getKeyCode();
if (suggestingPanel.suggestingNow) {
if (charCode == KeyCodes.KEY_ENTER || charCode == KeyCodes.KEY_TAB || event.getCharCode() == ' ') {
event.preventDefault();
suggestingPanel.insertCurrentKeyword();
return;
}
if (charCode == KeyCodes.KEY_DOWN) {
event.preventDefault();
suggestingPanel.panel.next();
return;
}
if (charCode == KeyCodes.KEY_UP) {
event.preventDefault();
suggestingPanel.panel.prev();
return;
}
} else {
// Позиции естественно посчитаны не совсем верно
int posX = textArea.getAbsoluteLeft();
int posY = textArea.getAbsoluteTop() + 20 * getCurrentLines();
suggestingPanel.setPopupPosition(posX, posY);
}
// Не предполагаем при удалении или смещении курсора
if (charCode == KeyCodes.KEY_BACKSPACE || charCode == KeyCodes.KEY_LEFT || charCode == KeyCodes.KEY_RIGHT) {
suggestingPanel.stopSuggesting();
return;
}
// События с нажатым Ctrl не обрабатываем (ну почти)
if(event.isControlKeyDown()){
if(event.getCharCode() == 'v' || event.getCharCode() == 'V'){
suggestingPanel.stopSuggesting();
}
return;
}
suggest(event.getCharCode());
}
});
}
private int getCurrentLines() {
// считает неверно если изменить размеры text area
return (this.getText().length() / this.getCharacterWidth()) + 1;
}
// Добавляет указаные символы после курсора
private void insertCharacters(String insertion) {
String text = this.getText();
int cursorPos = this.getCursorPos();
String res = text.substring(0, cursorPos) + insertion + text.substring(cursorPos);
setText(res);
setCursorPos(cursorPos + insertion.length());
suggestingPanel.stopSuggesting();
}
private void suggest(char c) {
// Отсекаем текст за курсором
int cursorPos = this.getCursorPos();
String text;
text = this.getText().substring(0, cursorPos) + (c == 0 ? "" : c);
if (text.length() == 0) {
this.suggestingPanel.setVisible(false);
return;
}
// получем вводимые символы
String keys = "";
RegExp pattern = RegExp.compile("\\b(\\w+)$", "gmi");
for (MatchResult result = pattern.exec(text); result != null; result = pattern.exec(text)) {
keys = result.getGroup(1);
}
if (!keys.equals("")) {
suggestingPanel.showMatches(keys);
}
}
// Панель для отображения предположений
class SuggestingPopupPanel extends PopupPanel {
private boolean suggestingNow = false;
private String suggestStyleName;
private List<String> keywords;
private Suggestions panel;
private List<String> currentSuggestions;
private String lastKeys;
public SuggestingPopupPanel(List<String> keywords, String suggestStyleName) {
super(true, false); // autohide, not modal
this.keywords = keywords;
this.suggestStyleName = suggestStyleName;
setVisible(false);
}
public void insertCurrentKeyword() {
insertCharacters(this.getKeywordEnd() + " ");
}
public String getKeywordEnd() {
return currentSuggestions.get(panel.current).substring(lastKeys.length());
}
public String getKeywordEnd(int index) {
return currentSuggestions.get(index).substring(lastKeys.length());
}
public void showMatches(String keys) {
lastKeys = keys;
// Получаем совпадения
List<String> suggestions = new LinkedList<String>();
RegExp pattern = RegExp.compile("\\b(" + keys + ")", "gmi");
for (String keyword : keywords) {
for (MatchResult result = pattern.exec(keyword); result != null; result = pattern.exec(keyword)) {
suggestions.add(keyword);
}
}
currentSuggestions = suggestions;
if (suggestions.isEmpty()) {
this.setVisible(false);
suggestingNow = false;
} else {
suggestingNow = true;
ArrayList<HTML> htmlList = new ArrayList<HTML>();
for (String suggestion : suggestions) {
String htmlText = HtmlHelper.getHtmlText(suggestion + "\n");
htmlText = applyStyle(htmlText, keys);
htmlList.add(new HTML(htmlText));
}
panel = new Suggestions(htmlList);
this.setWidget(panel);
this.setVisible(true);
this.show();
}
}
public void stopSuggesting(){
suggestingNow = false;
this.setVisible(false);
}
private String applyStyle(String text, String keys) {
String regex = "\\b" + keys.toLowerCase();
return text.replaceAll(regex, "<span class=\"" + suggestStyleName + "\">" + keys + "</span>");
}
// Отображает варианты
class Suggestions extends VerticalPanel {
String choosingName = "htmlFocus";
List<HTML> variants;
int current;
public Suggestions(final ArrayList<HTML> variants) {
if (variants.isEmpty()) {
return;
}
this.variants = variants;
current = 0;
variants.get(current).addStyleName(choosingName);
for (final HTML html : variants) {
html.addStyleName("suggestVariant");
// При нажатии дополняем соответсвующие символы
html.addClickHandler(new ClickHandler() {
public void onClick(ClickEvent event) {
textArea.insertCharacters(getKeywordEnd(variants.indexOf(html)) + " ");
stopSuggesting();
}
});
this.add(html);
}
}
public void prev() {
int prev = current - 1;
if (prev < 0) {
prev = variants.size() - 1;
}
variants.get(current).removeStyleName(choosingName);
variants.get(prev).addStyleName(choosingName);
current = prev;
}
public void next() {
int next = current + 1;
if (next == variants.size()) {
next = 0;
}
variants.get(current).removeStyleName(choosingName);
variants.get(next).addStyleName(choosingName);
current = next;
}
}
}
}
Excuse me for bad formatting and russian comments, but you should get the main idea.
Have you tried passing a TextArea to the SuggestBox's constructor? (given that TextArea extends TextBoxBase)
This is my current favourite solution of this: http://jdramaix.github.com/gwtchosen/
i think u can use the "comboBox" to that. with hide the arrow and make the field editable ..