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;
}
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).
Im supposed to create a Snake game using a Queue in Java.
I'm supposed to only use the three classes down below, however I do not know how I should modify my move() function in order to move the snake, since it is a Queue and I cannot access the tail of the snake.
I came up with the following:
Snake.java
import java.util.Random;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
public class Snake extends JFrame implements Runnable, KeyListener {
int length=40, width = 30;
int time;
int factor=10;
Specialqueue q;
int direction = 6;
Thread t;
int[][] food;
private boolean started;
public Snake() {
super("Snake");
setSize(length*factor+30, width*factor+60);
setVisible(true);
addKeyListener(this);
started = false;
time = 0;
}
public void paint(Graphics g){
if (g == null) return;
g.clearRect(0,0,getWidth(),getHeight());
if (!gestartet){
g.drawString("start the game by pressing 5",10,50);
g.drawString("Controll the snake with W,A,S,D",10,80);
return;
}
g.setColor(Color.blue);
for (int k = 0; k < length; k++)
for (int j = 0; j < breite; j++)
if (food[k][j]==1)
g.fillOval(k*10,20+j*10,10,10);
}
public void run() {
time = 0;
while (started){
try {Thread.sleep(300);}
catch (Exception e){};
move();
time++;
Graphics g = this.getGraphics();
}
}
public void stop() {
started=false;
t = null;
}
public void initFood() {
food = new int[length][breite];
for (int k = 0; k < length; k++) {
for (int j = 0; j < breite; j++) {
if (Math.random() < 0.01) futter[k][j] = 1;
else food[k][j] = 0;
}
}
}
public void initSnake(){
q = new Specialqueue();
direction = 6;
q.append(new Point(20,20));
q.append(new Point(19,20));
q.append(new Point(18,20));
q.append(new Point(17,20));
Graphics g = this.getGraphics();
repaint();
g.setColor(Color.red);
g.fillOval(20*10,20+20*10,10,10);
g.fillOval(19*10,20+20*10,10,10);
g.fillOval(18*10,20+20*10,10,10);
g.fillOval(17*10,20+20*10,10,10);
g.setColor(Color.black);
}
public void move()
{
Graphics g = this.getGraphics();
Point p = (Point)q.tail();
Point newPoint = null;
int size = 4;
if (direction == 6) {
for(int i=0;i<3;i++) {
q.remove();
}
for(int q=0;q<3;q++) {
newPoint = new Point(p.x+1, p.y);
}
if (newPoint.x >= length) {stoppe(); return;}
}
else if (direction == 4) {
newPoint = new Point(p.x-1, p.y);
if (newPoint.x < 0) {stoppe(); return;}
}
else if (direction == 8)
{
newPoint = new Point(p.x, p.y-1);
if (newPoint.y < 0) {stoppe(); return;}
}
else if (direction == 2)
{
newPoint = new Point(p.x, p.y+1);
if (newPoint.y >= width) {stoppe(); return;}
}
q.append(newPoint);
p = (Point)q.tail();
g.setColor(Color.red);
g.fillOval(p.x*10,20+p.y*10,10,10);
if(food[newPoint.x][newPoint.y] == 0){
p = (Point)q.first();
g.setColor(Color.white);
g.fillOval(p.x*10,20+p.y*10,10,10);
q.remove();
}
else {
food[newPoint.x][newPoint.y]=0;
}
}
public void keyPressed(KeyEvent ke)
{
char c = ke.getKeyChar();
if (c=='5' && started) {started = false; t = null; repaint(); return; }
if (c=='5' && !started){
gestartet=true;
initSnake();
initFutter();
t = new Thread(this);
try {Thread.sleep(150);} catch (Exception e){};
t.start();
return;
}
if ((c =='6' || c=='d') && direction != 4) direction = 6;
else if ((c =='2' || c=='s') && direction != 8) direction = 2;
else if ((c =='4' || c=='a') && direction != 6) direction = 4;
else if ((c =='8' || c=='w') && direction != 2) direction = 8;
}
}
SpecialQueue.java
public class Specialqueue <ContentType> {
Queue<ContentType> s;
public Specialqueue()
{
s = new Queue<ContentType>();
}
public ContentType tail(){
if (s.isEmpty()) return null;
return s.front();
}
public boolean isEmpty(){
return s.isEmpty();
}
public void append(ContentType pContent)
{
s.enqueue(pContent);
}
public void remove()
{
if(!s.isEmpty()) {
s.dequeue();
}
}
public ContentType first(){
if (this.isEmpty())
{
return null;
}
else{
return s.front();
}
}
}
**Queue.java**
public class Queue {
protected class QueueNode {
protected ContentType content = null;
protected QueueNode nextNode = null;
public QueueNode(ContentType pContent) {
content = pContent;
nextNode = null;
}
public void setNext(QueueNode pNext) {
nextNode = pNext;
}
public QueueNode getNext() {
return nextNode;
}
public ContentType getContent() {
return content;
}
}
protected QueueNode head;
protected QueueNode tail;
public Queue() {
head = null;
tail = null;
}
public boolean isEmpty() {
return head == null;
}
public void enqueue(ContentType pContent) {
if (pContent != null) {
QueueNode newNode = new QueueNode(pContent);
if (this.isEmpty()) {
head = newNode;
tail = newNode;
} else {
tail.setNext(newNode);
tail = newNode;
}
}
}
public void dequeue() {
if (!this.isEmpty()) {
head = head.getNext();
if (this.isEmpty()) {
head = null;
tail = null;
}
}
}
public ContentType front() {
if (this.isEmpty()) {
return null;
} else {
return head.getContent();
}
}
}
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
In GXT is an example:
http://www.sencha.com/examples/#ExamplePlace:paginggrid
Where I can see realization of this method:
service.getPosts(loadConfig, callback);
or any other similar service
For example, here -
http://spring-rapid.googlecode.com/svn/trunk/atom-explorer/src/main/java/com/atom/ebank/wfront/examples/resources/server/ExampleServiceImpl.java
...
#Override
public PagingLoadResult<Post> getPosts(PagingLoadConfig config) {
if (posts == null) {
loadPosts();
}
if (config.getSortInfo().size() > 0) {
SortInfo sort = config.getSortInfo().get(0);
if (sort.getSortField() != null) {
final String sortField = sort.getSortField();
if (sortField != null) {
Collections.sort(posts, sort.getSortDir().comparator(new Comparator<Post>() {
public int compare(Post p1, Post p2) {
if (sortField.equals("forum")) {
return p1.getForum().compareTo(p2.getForum());
} else if (sortField.equals("username")) {
return p1.getUsername().compareTo(p2.getUsername());
} else if (sortField.equals("subject")) {
return p1.getSubject().compareTo(p2.getSubject());
} else if (sortField.equals("date")) {
return p1.getDate().compareTo(p2.getDate());
}
return 0;
}
}));
}
}
}
ArrayList<Post> sublist = new ArrayList<Post>();
int start = config.getOffset();
int limit = posts.size();
if (config.getLimit() > 0) {
limit = Math.min(start + config.getLimit(), limit);
}
for (int i = config.getOffset(); i < limit; i++) {
sublist.add(posts.get(i));
}
return new PagingLoadResultBean<Post>(sublist, posts.size(), config.getOffset());
}
...
I have this applet and i cant figure out why it doesnt load on html page.I have added full permissions in java.policy file. I use the default html file from NetBeans Applet's output.
/* Hearts Cards Game with AI*/
import java.applet.Applet;
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Random;
import javax.swing.JOptionPane;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import java.awt.Graphics;
import java.awt.Image;
import java.security.AccessController;
import javax.swing.ImageIcon;
import javax.swing.*;
import javax.swing.JPanel;
public class Game extends JApplet implements MouseListener, Runnable {
int initNoCards = 13;
int width, height;
boolean endGame = false;
int turn = -1;
int firstCard = 0;
int firstTrick = 0;
String leadingSuit = null;
Cards leadingCard = null;
Cards playCard = null;
String startCard = "c2";
Cards[] trickCards = new Cards[4];
ArrayList<Cards>[] playerCards = new ArrayList[4];
ArrayList<Cards>[] takenCards = new ArrayList[4];
boolean heartsBroken = false;
ArrayList<Cards> cards = new ArrayList<Cards>();
String[] hearts = {"h2", "h3", "h4", "h5", "h6", "h7", "h8", "h9", "h10", "h12", "h13", "h14", "h15"};
String queen = "s13";
int cardHeight = 76;
int cardWidth = 48;
ArrayList<Rectangle> rectangles = new ArrayList<Rectangle>();
int selectedCard = -1;
//set the background image
Image backImage = new ImageIcon("deck\\back2.png").getImage();
public void GetDataFromXML() {
try {
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser saxParser = factory.newSAXParser();
DefaultHandler handler = new DefaultHandler() {
boolean name = false;
boolean image = false;
#Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
if (qName.equalsIgnoreCase("NAME")) {
name = true;
}
if (qName.equalsIgnoreCase("IMAGE")) {
image = true;
}
}
#Override
public void endElement(String uri, String localName,
String qName) throws SAXException {
}
#Override
public void characters(char ch[], int start, int length) throws SAXException {
String s = new String(ch, start, length);
if (name) {
cards.add(new Cards(s));
name = false;
}
if (image) {
image = false;
}
}
};
saxParser.parse("deck\\deck.xml", handler);
} catch (Exception e) {
}
}
//function for comparing cards from same suite
public boolean lowerThan(Cards c1, Cards c2) {
int a, b;
a = Integer.parseInt(c1.getName().substring(1));
b = Integer.parseInt(c2.getName().substring(1));
return a < b;
}
//checks if a card is valid to play
public boolean ValidMove(Cards c) {
if (firstCard == 0) {
if (c.getName().equals(startCard)) {
firstCard = 1;
return true;
}
return false;
}
boolean result = playerCards[turn].indexOf(c) >= 0;
if (leadingSuit == null) {
return result;
}
boolean found = false;
for (int i = 0; i < playerCards[turn].size(); i++) {
if (playerCards[turn].get(i).getName().charAt(0) == leadingSuit.charAt(0)) {
found = true;
break;
}
}
if (!found) {
boolean justHearts = true;
for (int i = 0; i < playerCards[turn].size(); i++) {
if (playerCards[turn].get(i).getName().charAt(0) != 'h') {
justHearts = false;
break;
}
}
if (firstTrick == 0) {
if (c.getName().equals(queen)) {
return false;
}
if (!justHearts && c.getName().charAt(0) == 'h') {
return false;
}
} else {
if (c.getName().charAt(0) == 'h' && leadingSuit == null && !heartsBroken && !justHearts) {
return false;
}
}
} else {
if (c.getName().charAt(0) != leadingSuit.charAt(0)) {
return false;
}
}
return result;
}
#Override
public void init() {
GetDataFromXML();
setSize(500, 500);
width = super.getSize().width;
height = super.getSize().height;
setBackground(Color.white);
addMouseListener(this);
for (int i = 0; i < cards.size(); i++) {
System.out.println(cards.get(i).getName());
System.out.println(cards.get(i).getImage());
}
Shuffle();
}
public int GetTrickCount() {
int count = 0;
for (int i = 0; i < trickCards.length; i++) {
if (trickCards[i] != null) {
count++;
}
}
return count;
}
public void ResetTrick() {
for (int i = 0; i < trickCards.length; i++) {
trickCards[i] = null;
}
}
#Override
public void run() {
try {
PlayTurn();
} catch (InterruptedException ex) {
}
}
public void start() {
Thread th = new Thread(this);
th.start();
}
//function for shuffling cards and painting players cards
public void Shuffle() {
for (int i = 0; i < 4; i++) {
playerCards[i] = new ArrayList<Cards>();
takenCards[i] = new ArrayList<Cards>();
}
ArrayList<Cards> list = new ArrayList<Cards>();
list.addAll(cards);
Collections.shuffle(list);
for (int i = 0; i < list.size(); i++) {
System.out.print(list.get(i).getName() + " ");
}
//initializare liste carti
for (int i = 0; i < 4; i++) {
playerCards[i] = new ArrayList<Cards>();
takenCards[i] = new ArrayList<Cards>();
for (int j = 0; j < initNoCards; j++) {
playerCards[i].add((list.get(j + i * initNoCards)));
if (list.get(j + i * initNoCards).getName().equals(startCard)) {
turn = i;
}
}
Collections.sort(playerCards[i], c);
ShowCards(i);
}
for (int i = 0; i < playerCards[0].size() - 1; i++) {
rectangles.add(new Rectangle((141 + 1) + 13 * i - 2, 350 + 1, 13 - 2, cardHeight - 1));
}
rectangles.add(new Rectangle((141 + 1) + 13 * 12 - 2, 350 + 1, cardWidth, cardHeight - 1));
ShowPlayersCards();
}
Comparator<Cards> c = new Comparator<Cards>() {
#Override
public int compare(Cards o1, Cards o2) {
if (o2.getName().charAt(0) != o1.getName().charAt(0)) {
return o2.getName().charAt(0) - o1.getName().charAt(0);
} else {
int a, b;
a = Integer.parseInt(o1.getName().substring(1));
b = Integer.parseInt(o2.getName().substring(1));
return a - b;
}
}
};
public void PlayTurn() throws InterruptedException {
endGame = true;
System.out.println("Its " + turn);
for (int i = 0; i < 4; i++) {
if (!playerCards[i].isEmpty()) {
endGame = false;
}
}
if (endGame) {
System.out.println("Game over!");
GetPlayersScore();
return;
}
if (turn != 0) {
Random r = new Random();
int k = r.nextInt(playerCards[turn].size());
Cards AIcard = playerCards[turn].get(k);
while (!ValidMove(AIcard)) {
k = r.nextInt(playerCards[turn].size());
AIcard = playerCards[turn].get(k);
}
leadingCard = AIcard;
playCard = AIcard;
} else {
System.out.println("\nIt is player's (" + turn + ") turn");
System.out.println("Player (" + turn + ") enter card to play:");
leadingCard = null;
playCard = null;//new Cards(read);
while (true) {
if (playCard != null) {
break;
}
Thread.sleep(50);
}
}
repaint();
Thread.sleep(1000);
repaint();
if (playCard.getName().charAt(0) == 'h') {
heartsBroken = true;
}
playerCards[turn].remove(playCard);
trickCards[turn] = playCard;
if (GetTrickCount() == 1)//setez leading suit doar pentru trickCards[0]
{
leadingSuit = GetSuit(playCard);
}
System.out.println("Leading suit " + leadingSuit);
System.out.println("Player (" + turn + ") chose card " + playCard.getName() + " to play");
ShowTrickCards();
ShowPlayersCards();
if (GetTrickCount() < 4) {
turn = (turn + 1) % 4;
} else {
turn = GetTrickWinner();
leadingSuit = null;
firstTrick = 1;
playCard = null;
repaint();
}
PlayTurn();
}
public void ShowTrickCards() {
System.out.println("Cards in this trick are:");
for (int i = 0; i < 4; i++) {
if (trickCards[i] != null) {
System.out.print(trickCards[i].getName() + " ");
}
}
}
public String GetSuit(Cards c) {
if (c.getName().contains("c")) {
return "c";
}
if (c.getName().contains("s")) {
return "s";
}
if (c.getName().contains("h")) {
return "h";
}
if (c.getName().contains("d")) {
return "d";
}
return null;
}
public String GetValue(Cards c) {
String get = null;
get = c.getName().substring(1);
return get;
}
public int GetTrickWinner() {
int poz = 0;
for (int i = 1; i < 4; i++) {
if (trickCards[poz].getName().charAt(0) == trickCards[i].getName().charAt(0) && lowerThan(trickCards[poz], trickCards[i]) == true) {
poz = i;
}
}
System.out.println("\nPlayer (" + poz + ") won last trick with card " + trickCards[poz].getName());
ResetTrick();
return poz;
}
public void ShowPlayersCards() {
ShowCards(0);
ShowCards(1);
ShowCards(2);
ShowCards(3);
}
public void GetPlayersScore() {
GetScore(0);
GetScore(1);
GetScore(2);
GetScore(3);
}
public void ShowCards(int player) {
System.out.print("\nPlayer (" + player + ") cards: ");
for (int i = 0; i < playerCards[player].size(); i++) {
System.out.print(playerCards[player].get(i).getName() + " ");
}
System.out.println();
}
public int GetScore(int player) {
int score = 0;
for (int i = 0; i < takenCards[player].size(); i++) {
for (int j = 0; j < hearts.length; j++) {
if (takenCards[player].get(i).getName().equals(hearts[j])) {
score++;
break;
}
}
if (takenCards[player].get(i).getName().equals(queen)) {
score += 13;
}
}
return score;
}
#Override
public void paint(Graphics g) {
g.drawImage(backImage, 0, 0, getWidth(), getHeight(), this);
for (int i = 0; i < playerCards[0].size(); i++) {
if (selectedCard == i) {
g.drawImage(playerCards[0].get(i).getImage(), 141 + i * 13, 340, null);
} else {
g.drawImage(playerCards[0].get(i).getImage(), 141 + i * 13, 350, null);
}
if (trickCards[0] != null) {
g.drawImage(trickCards[0].getImage(), 225, 250, 48, 76, null);
}
if (trickCards[1] != null) {
g.drawImage(trickCards[1].getImage(), 177, 174, 48, 76, null);
}
if (trickCards[2] != null) {
g.drawImage(trickCards[2].getImage(), 225, 98, 48, 76, null);
}
if (trickCards[3] != null) {
g.drawImage(trickCards[3].getImage(), 273, 174, 48, 76, null);
}
}
}
#Override
public void mouseClicked(MouseEvent e) {
if (turn != 0) {
return;
}
for (int i = 0; i < rectangles.size(); i++) {
if (rectangles.get(i).contains(e.getPoint())) {
if (i == selectedCard) {
if (ValidMove(playerCards[0].get(i))) {
selectedCard = -1;
rectangles.get(rectangles.size() - 2).width = rectangles.get(rectangles.size() - 1).width;
playCard = playerCards[0].get(i);
leadingCard = playCard;
rectangles.remove(rectangles.size() - 1);
trickCards[0] = playerCards[0].remove(i);
} else {
if (firstCard == 0) {
JOptionPane.showMessageDialog(this, "You have to play 2 of clubs!");
}
}
} else {
selectedCard = i;
rectangles.get(i).y -= 10;
}
repaint();
break;
}
}
}
#Override
public void mousePressed(MouseEvent e) {
}
#Override
public void mouseReleased(MouseEvent e) {
}
#Override
public void mouseEntered(MouseEvent e) {
}
#Override
public void mouseExited(MouseEvent e) {
}
}
class Cards extends JPanel {
private String name;
private String image;
private Image img;
public Cards(String name) {
super();
this.name = name;
this.image = "deck\\" + name + ".png";
this.img = new ImageIcon(image).getImage();
}
public Cards() {
super();
this.name = null;
this.image = null;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Image getImage() {
return img;
}
public void setImage(String image) {
this.image = image;
}
#Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (!(obj instanceof Cards)) {
return false;
}
Cards c = (Cards) obj;
return name.equals(c.getName()) && image.equals(c.getImage());
}
#Override
public int hashCode() {
int hash = 7;
hash = 31 * hash + (this.name != null ? this.name.hashCode() : 0);
hash = 31 * hash + (this.image != null ? this.image.hashCode() : 0);
return hash;
}
#Override
public void paint(Graphics g) {
g.drawImage(img, WIDTH, HEIGHT, this);
}
public boolean lowerThan(Cards c1, Cards c2) {
int a, b;
a = Integer.parseInt(c1.getName().substring(1));
b = Integer.parseInt(c2.getName().substring(1));
return a < b;
}
public int compareTo(Cards c) {
if (c.getName().charAt(0) != name.charAt(0)) {
return c.getName().charAt(0) - name.charAt(0);
} else {
int a, b;
a = Integer.parseInt(name.substring(1));
b = Integer.parseInt(c.getName().substring(1));
return a - b;
}
}
}
HTML
<HTML>
<HEAD>
<TITLE>Applet HTML Page</TITLE>
</HEAD>
<BODY>
<H3><HR WIDTH="100%">Applet HTML Page<HR WIDTH="100%"></H3>
<P>
<APPLET codebase="classes" code="Game.class" width=350 height=200></APPLET>
</P>
<HR WIDTH="100%"><FONT SIZE=-1><I>Generated by NetBeans IDE</I></FONT>
</BODY>
</HTML>
Image backImage = new ImageIcon("deck\\back2.png").getImage();
If I am the user of the applet when it is on the internet, the will cause the JRE to search for a File relative to the current user directory on my PC, either that or the cache of FF. In either case, it will not locate an image by the name of back2.png.
For fear of sounding like a looping Clip:
Resources intended for an applet (icons, BG image, help files etc.) should be accessed by URL.
An applet will not need trust to access those resources, so long as the resources are on the run-time class-path, or on the same server as the code base or document base.
Further
I have added full permissions in java.policy file.
This is pointless. It will not be workable at time of deployment unless you control every machine it is intended to run on. If an applet needs trust in a general environment, it needs to be digitally signed. You might as well sign it while building the app.
cant figure out why it doesnt load on html page.
Something that would assist greatly is to configure the Java Console to open when an applet is loaded. There is a setting in the last tab of the Java Control Panel that configures it.