i am trying to update a 1.7 class to 1.12.2. i fixed some errors but i dont know how to fix the other errors. if anyone have a suggestion, i would be very very happy...
The Class:
package de.beastsoup.utils.spigot.bo2;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import de.beastsoup.utils.spigot.BeastUtils;
import net.minecraft.server.v1_12_R1.TileEntity;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.block.Block;
import org.bukkit.craftbukkit.v1_12_R1.CraftWorld;
import org.bukkit.scheduler.BukkitRunnable;
public class BO2 {
private Arena arena;
public BO2() {
this.arena = new Arena(this);
}
public Arena getArena() {
return arena;
}
private static HashSet<Location> blocksForUpdate = new HashSet<>();
public void addBlockUpdate(Location location) {
blocksForUpdate.add(location);
}
public void startUpdate() {
new BukkitRunnable() {
#Override
public void run() {
if (!blocksForUpdate.isEmpty()) {
net.minecraft.server.v1_12_R1.World world = ((CraftWorld) Bukkit.getWorlds().get(0)).getHandle();
for (Location location : blocksForUpdate) {
world.notify(location.getBlockX(), location.getBlockY(), location.getBlockZ());
}
blocksForUpdate.clear();
}
}
}.runTaskTimer(BeastUtils.getPlugin(BeastUtils.class), 1, 1);
}
/* Spawn BO2 */
public List<Block> spawn(Location location, File file) {
long time = System.currentTimeMillis();
BufferedReader reader;
ArrayList<Block> blocks = new ArrayList<>();
try {
reader = new BufferedReader(new FileReader(file));
String line = null;
while ((line = reader.readLine()) != null) {
if (!line.contains(",") || !line.contains(":")) {
continue;
}
String[] parts = line.split(":");
String[] coordinates = parts[0].split(",");
String[] blockData = parts[1].split("\\.");
setBlockFast(location.getWorld(), location.getBlockX() + Integer.valueOf(coordinates[0]), location.getBlockY() + Integer.valueOf(coordinates[2]), location.getBlockZ() + Integer.valueOf(coordinates[1]), Integer.valueOf(blockData[0]), blockData.length > 1 ? Byte.valueOf(blockData[1]) : 0);
blocks.add(location.getWorld().getBlockAt(location.getBlockX() + Integer.valueOf(coordinates[0]), location.getBlockY() + Integer.valueOf(coordinates[2]), location.getBlockZ() + Integer.valueOf(coordinates[1])));
}
reader.close();
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("BO2 spawnada em " + (time - System.currentTimeMillis()) + "ms");
return blocks;
}
/* Load BO2 file */
public List<FutureBlock> load(Location location, File file) {
BufferedReader reader;
ArrayList<FutureBlock> blocks = new ArrayList<>();
try {
reader = new BufferedReader(new FileReader(file));
String line = null;
while ((line = reader.readLine()) != null) {
if (!line.contains(",") || !line.contains(":")) {
continue;
}
String[] parts = line.split(":");
String[] coordinates = parts[0].split(",");
String[] blockData = parts[1].split("\\.");
blocks.add(new FutureBlock(location.clone().add(Integer.valueOf(coordinates[0]), Integer.valueOf(coordinates[2]), Integer.valueOf(coordinates[1])), Integer.valueOf(blockData[0]), blockData.length > 1 ? Byte.valueOf(blockData[1]) : 0));
}
reader.close();
} catch (Exception e) {
e.printStackTrace();
}
return blocks;
}
/* Set methods */
public boolean setBlockFast(World world, int x, int y, int z, int blockId, byte data) {
if (y >= 255 || y < 0) {
return false;
}
net.minecraft.server.v1_12_R1.World w = ((CraftWorld) world).getHandle();
net.minecraft.server.v1_12_R1.Chunk chunk = w.getChunkAt(x >> 4, z >> 4);
boolean b = data(chunk, x & 0x0f, y, z & 0x0f, net.minecraft.server.v1_12_R1.Block.getById(blockId), data);
addBlockUpdate(new Location(Bukkit.getWorlds().get(0), x, y, z));
return b;
}
#SuppressWarnings("deprecation")
public boolean setBlockFast(Location location, Material material, byte data) {
return setBlockFast(location.getWorld(), location.getBlockX(), location.getBlockY(), location.getBlockZ(), material.getId(), data);
}
private boolean data(net.minecraft.server.v1_12_R1.Chunk that, int i, int j, int k, net.minecraft.server.v1_12_R1.Block block, int l) {
int i1 = k << 4 | i;
if (j >= that.b[i1] - 1) {
that.b[i1] = -999;
}
int j1 = that.heightMap[i1];
net.minecraft.server.v1_12_R1.Block block1 = that.getType(i, j, k);
int k1 = that.getData(i, j, k);
if (block1 == block && k1 == l) {
return false;
} else {
boolean flag = false;
net.minecraft.server.v1_12_R1.ChunkSection chunksection = that.getSections()[j >> 4];
if (chunksection == null) {
if (block == net.minecraft.server.v1_12_R1.Blocks.AIR) {
return false;
}
chunksection = that.getSections()[j >> 4] = new net.minecraft.server.v1_12_R1.ChunkSection(j >> 4 << 4, !that.world.worldProvider.g);
flag = j >= j1;
}
int l1 = that.locX * 16 + i;
int i2 = that.locZ * 16 + k;
if (!that.world.isStatic) {
block1.f(that.world, l1, j, i2, k1);
}
if (!(block1 instanceof IContainer)) {
chunksection.setTypeId(i, j & 15, k, block);
}
if (!that.world.isStatic) {
block1.remove(that.world, l1, j, i2, block1, k1);
} else if (block1 instanceof IContainer && block1 != block) {
that.world.p(l1, j, i2);
}
if (block1 instanceof IContainer) {
chunksection.setTypeId(i, j & 15, k, block);
}
if (chunksection.getTypeId(i, j & 15, k) != block) {
return false;
} else {
chunksection.setData(i, j & 15, k, l);
if (flag) {
that.initLighting();
}
TileEntity tileentity;
if (block1 instanceof IContainer) {
tileentity = that.e(i, j, k);
if (tileentity != null) {
tileentity.u();
}
}
if (!that.world.isStatic && (!that.world.captureBlockStates || (block instanceof net.minecraft.server.v1_7_R4.BlockContainer))) {
block.onPlace(that.world, l1, j, i2);
}
if (block instanceof IContainer) {
if (that.getType(i, j, k) != block) {
return false;
}
tileentity = that.e(i, j, k);
if (tileentity == null) {
tileentity = ((IContainer) block).a(that.world, l);
that.world.setTileEntity(l1, j, i2, tileentity);
}
if (tileentity != null) {
tileentity.u();
}
}
that.n = true;
return true;
}
}
}
/* FutureBlock Utils */
public class FutureBlock {
private Location location;
private int id;
private byte data;
public FutureBlock(Location location, int id, byte data) {
this.location = location;
this.id = id;
this.data = data;
}
public byte getData() {
return data;
}
public Location getLocation() {
return location;
}
public int getId() {
return id;
}
#SuppressWarnings("deprecation")
public void place() {
location.getBlock().setTypeIdAndData(id, data, true);
}
}
}
This Error i need fix now: https://gyazo.com/cb3176c9d879532adddfc5ce1edad2eb , https://gyazo.com/014047f5103fd1eaace121bc121fa8dc , https://gyazo.com/6b546cd147037a9deffad42e3b1ce1ef
if anyone know nms spigot 1.12.2 or something i would be happy
I'm not sure about that third image (I don't see an error in it), and you're going to look at the Spigot docs for specific information on how to fix these, but I can tell you that they're related to vanilla moving from an X,Y,Z position (specified as 3 separate ints) to a BlockPos system (specified as a single class instance containing the 3 ints, along with various helper methods, such as up() and east()).
Both of the first two images/errors are that the method you're calling needs a BlockPos passed and you're giving it three ints.
I don't know where the ints are coming from in the second, and for the first, I don't know what Spigot's Location object is or where those values are coming from and how they're constructed.
But this should give you enough information to resolve these types of errors on your own now.
Related
I have a graph that contains objects of type GraphNodes. These nodes contain an object City that has properties if It's infected or not. I want to loop through all the nodes and check if a city is infected or not. I have a generic method getInfo which returns an object of type E in my case City. But when i try to chain another method or to get property i can't see them as if they are not available. All the classes in the code are from college so i can't add/remove methods. I've tried with foreach but I still can't get the methods.
Code:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.Stack;
import java.util.StringTokenizer;
import java.util.LinkedList;
class City {
String osnovna_granka;
boolean zarazen;
City(String osnovna_granka, boolean zarazen) {
this.osnovna_granka = osnovna_granka;
this.zarazen = zarazen;
}
#Override
public String toString() {
if (zarazen == true) {
return osnovna_granka + " zarazen";
} else {
return osnovna_granka + " nezarazen";
}
}
}
class Graph {
int num_nodes;
GraphNode<City> adjList[];
#SuppressWarnings("unchecked")
public Graph(int num_nodes) {
this.num_nodes = num_nodes;
adjList = (GraphNode<City>[]) new GraphNode[num_nodes];
}
int adjacent(int x, int y) {
// proveruva dali ima vrska od jazelot so
// indeks x do jazelot so indeks y
return (adjList[x].containsNeighbor(adjList[y])) ? 1 : 0;
}
void addEdge(int x, int y) {
// dodava vrska od jazelot so indeks x do jazelot so indeks y
if (!adjList[x].containsNeighbor(adjList[y])) {
adjList[x].addNeighbor(adjList[y]);
}
}
void deleteEdge(int x, int y) {
adjList[x].removeNeighbor(adjList[y]);
}
#Override
public String toString() {
String ret = new String();
for (int i = 0; i < this.num_nodes; i++) {
ret += i + ": " + adjList[i] + "\n";
}
return ret;
}
}
class GraphNode<E> {
private int index;//index (reden broj) na temeto vo grafot
private E info;
private LinkedList<GraphNode<E>> neighbors;
public GraphNode(int index, E info) {
this.index = index;
this.info = info;
neighbors = new LinkedList<GraphNode<E>>();
}
boolean containsNeighbor(GraphNode<E> o) {
return neighbors.contains(o);
}
void addNeighbor(GraphNode<E> o) {
neighbors.add(o);
}
void removeNeighbor(GraphNode<E> o) {
if (neighbors.contains(o)) {
neighbors.remove(o);
}
}
#Override
public String toString() {
String ret = "INFO:" + info + " SOSEDI:";
for (int i = 0; i < neighbors.size(); i++) {
ret += neighbors.get(i).info + " ";
}
return ret;
}
#Override
public boolean equals(Object obj) {
#SuppressWarnings("unchecked")
GraphNode<E> pom = (GraphNode<E>) obj;
return (pom.info.equals(this.info));
}
public int getIndex() {
return index;
}
public void setIndex(int index) {
this.index = index;
}
public E getInfo() {
return info;
}
public void setInfo(E info) {
this.info = info;
}
public LinkedList<GraphNode<E>> getNeighbors() {
return neighbors;
}
public void setNeighbors(LinkedList<GraphNode<E>> neighbors) {
this.neighbors = neighbors;
}
}
public class Main {
public static void main(String[] args) throws Exception {
int i, j, k;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int N = Integer.parseInt(br.readLine());
Graph g = new Graph(N);
for (i = 0; i < N; i++) {
StringTokenizer st = new StringTokenizer(br.readLine());
st.nextToken();
String osnovna_granka = st.nextToken();
String str_zarazen = st.nextToken();
if (str_zarazen.equals("zarazen")) {
g.adjList[i] = new GraphNode(i, new City(osnovna_granka, true));
} else {
g.adjList[i] = new GraphNode(i, new City(osnovna_granka, false));
}
}
int M = Integer.parseInt(br.readLine());
for (i = 0; i < M; i++) {
StringTokenizer st = new StringTokenizer(br.readLine());
int a = Integer.parseInt(st.nextToken());
int b = Integer.parseInt(st.nextToken());
g.addEdge(a, b);
g.addEdge(b, a);
}
br.close();
Stack<GraphNode> stack = new Stack<>();
int counter = 0;
// vasiot kod ovde;
for(GraphNode gn: g.adjList) {
gn.getInfo().// Here the properties of City should show up
}
}
}
GraphNode is a generic type and you have not specified the type, the IDE cannot infer the type so no methods can be suggested. in the for loop you need to specify the type of the GraphNode.
for(GraphNode<City> gn: g.adjList)
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 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();
}
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.
I am learning how to use Java and I want to make a text scroller for my website.
I have found a similar scroller that I want to add but I want to look at the code to see how it was done.
The applet can be found here: http://www.javascriptkit.com/java/java20.shtml
The problem is when I try to open the class file within notepad the encoding or text shows up with strange characters instead of showing me the code.
Please can someone let me know if there is any possible way of me seeing the code for this class.
Thanks
That is a class file meaning it is compiled code so you can not see it's source.
In order to see the source, you need the .java file which is the file which you compile to get the byte code.
It seems the site is just providing the compiled class, and you never know using it they might have some hidden functionality in the class as well e.g to send information to the owner servers etc.
EDIT:
So here is the de-compiled code of applet written by ProScroll version 2.3 by Slava Pestov
import java.applet.Applet;
import java.applet.AppletContext;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Event;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.MediaTracker;
import java.awt.Toolkit;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.Enumeration;
import java.util.StringTokenizer;
import java.util.Vector;
public class ProScroll extends Applet
implements Runnable
{
private Thread thread;
private Image image;
private int scrollLength;
private int scrolled;
private int speed = 10;
private int imgsWidth;
private URL url;
private String target;
private Color bgColor;
public void init()
{
int i = 12; int j = 0;
String str2 = getParameter("TEXT");
String str3 = getParameter("TEXTURL");
if ((str2 == null) && (str3 == null)) {
str2 = "No TEXT or TEXTURL parameter specified";
}
if (str3 != null)
{
localObject = new StringBuffer();
try
{
InputStream localInputStream = new URL(str3)
.openConnection().getInputStream();
while (true)
{
int k = localInputStream.read();
if (k == -1) break;
if (k != 10) {
if (k == 9) { ((StringBuffer)localObject).append(' '); continue; }
((StringBuffer)localObject).append((char)k);
}
}
localInputStream.close();
str2 = ((StringBuffer)localObject).toString();
}
catch (Exception localException1)
{
if (str2 == null) {
str2 = "Error loading text from URL: " + localException1;
}
}
}
String str1 = getParameter("FONT");
if (str1 == null) str1 = "TimesRoman";
this.target = getParameter("TARGET");
if (this.target == null) this.target = "_self";
try
{
i = Integer.parseInt(getParameter("SIZE"));
}
catch (Exception localException2)
{
}
Object localObject = getParameter("STYLE");
if ("bold".equals(localObject)) j = 1;
else if ("italic".equals(localObject)) j = 2;
else if ("bolditalic".equals(localObject)) j = 3;
String str4 = getParameter("SPEED");
if ("slow".equals(str4)) this.speed = 20;
else if ("medium".equals(str4)) this.speed = 15; else {
this.speed = 10;
}
try
{
this.url = new URL(getDocumentBase(), getParameter("URL"));
}
catch (Exception localException3)
{
}
this.bgColor = parseColorName(getParameter("BGCOLOR"), Color.black);
Enumeration localEnumeration = parseAndLoadImages(getParameter("IMAGES"));
Font localFont = new Font(str1, j, i);
FontMetrics localFontMetrics = getToolkit().getFontMetrics(localFont);
this.image = createImage(localFontMetrics.stringWidth(str2) + this.imgsWidth + size().width, size().height);
this.scrolled = (-size().width);
parseAndDrawText(this.image.getGraphics(), str2, localFontMetrics, localFont, localEnumeration);
}
private void parseAndDrawText(Graphics paramGraphics, String paramString, FontMetrics paramFontMetrics, Font paramFont, Enumeration paramEnumeration)
{
paramGraphics.setFont(paramFont);
paramGraphics.setColor(this.bgColor);
paramGraphics.fillRect(0, 0, this.image.getWidth(this), this.image.getHeight(this));
paramGraphics.setColor(Color.white);
StringBuffer localStringBuffer = new StringBuffer();
int i = 0; int j = 0;
for (int k = 0; k < paramString.length(); k++)
{
char c = paramString.charAt(k);
if ((c == '#') && (j == 0))
{
if (i != 0)
{
paramGraphics.setColor(parseColorName(localStringBuffer.toString(), Color.white));
localStringBuffer.setLength(0);
i = 0;
}
else
{
i = 1;
}
}
else if ((c == '$') && (i == 0) && (j == 0))
{
try
{
Image localImage = (Image)paramEnumeration.nextElement();
paramGraphics.drawImage(localImage, this.scrollLength, 0, this);
this.scrollLength += localImage.getWidth(this);
}
catch (Exception localException)
{
}
}
else if ((c == '/') && (j == 0))
{
j = 1;
}
else if (i != 0)
{
localStringBuffer.append(c);
}
else
{
if (j == 1) j = 0;
paramGraphics.drawString(String.valueOf(c), this.scrollLength, paramFontMetrics.getAscent());
this.scrollLength += paramFontMetrics.charWidth(c);
}
}
}
private Color parseColorName(String paramString, Color paramColor)
{
if ("red".equals(paramString)) return Color.red;
if ("green".equals(paramString)) return Color.green;
if ("blue".equals(paramString)) return Color.blue;
if ("yellow".equals(paramString)) return Color.yellow;
if ("orange".equals(paramString)) return Color.orange;
if ("white".equals(paramString)) return Color.white;
if ("lightGray".equals(paramString)) return Color.lightGray;
if ("gray".equals(paramString)) return Color.gray;
if ("darkGray".equals(paramString)) return Color.darkGray;
if ("black".equals(paramString)) return Color.black;
if ("cyan".equals(paramString)) return Color.cyan;
if ("magenta".equals(paramString)) return Color.magenta;
if ("pink".equals(paramString)) return Color.pink;
return paramColor;
}
private Enumeration parseAndLoadImages(String paramString)
{
if (paramString == null) return null;
int i = 0;
Vector localVector = new Vector();
StringTokenizer localStringTokenizer = new StringTokenizer(paramString);
MediaTracker localMediaTracker = new MediaTracker(this);
while (localStringTokenizer.hasMoreTokens())
{
try
{
Image localImage = getImage(new URL(getDocumentBase(), localStringTokenizer.nextToken()));
localVector.addElement(localImage);
localMediaTracker.addImage(localImage, i);
localMediaTracker.waitForID(i++);
this.imgsWidth += localImage.getWidth(this);
}
catch (Exception localException)
{
}
}
return localVector.elements();
}
public void start()
{
this.thread = new Thread(this);
this.thread.start();
}
public void stop()
{
this.thread = null;
this.scrolled = (-size().width);
}
public void run()
{
while (Thread.currentThread() == this.thread)
{
long l = System.currentTimeMillis();
if (++this.scrolled > this.scrollLength) this.scrolled = (-size().width);
repaint();
try
{
Thread.sleep(Math.max(this.speed - (System.currentTimeMillis() - l), 0L));
}
catch (InterruptedException localInterruptedException)
{
}
}
}
public boolean mouseEnter(Event paramEvent, int paramInt1, int paramInt2)
{
if (this.url != null) getAppletContext().showStatus("Link: " + this.url.toString());
return true;
}
public boolean mouseExit(Event paramEvent, int paramInt1, int paramInt2)
{
if (this.url != null) getAppletContext().showStatus("");
return true;
}
public boolean mouseUp(Event paramEvent, int paramInt1, int paramInt2)
{
if (this.url != null) getAppletContext().showDocument(this.url, this.target);
return true;
}
public void update(Graphics paramGraphics)
{
paramGraphics.setColor(this.bgColor);
if (this.scrolled < 0)
{
paramGraphics.setColor(this.bgColor);
paramGraphics.fillRect(0, 0, -this.scrolled, size().height);
}
paramGraphics.drawImage(this.image, -this.scrolled, 0, this);
}
public void paint(Graphics paramGraphics)
{
update(paramGraphics);
}
public String getAppletInfo()
{
return "ProScroll version 2.3 by Slava Pestov";
}
}
a java .class file is a compiled file that you cannot read with notepad.
if you want the source code you should try to ask it to the author of the article or you could decompile it.