fix class icontainer minecraft spigot - java

Can anyone make me this class 1.12.2 compatible? I tried it many times but without success. I would be happy if anyone is so nice. And don't come with learning java or whatever I am new at this learning by doing Example IContainer. this is not in 1.12.2. or world.notify();. I do not know what should I add to make this compatible? the owner of this utils is not active anymore so I cant ask.
package utils;
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 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_7_R4.CraftWorld;
import org.bukkit.scheduler.BukkitRunnable;
import net.minecraft.server.v1_7_R4.IContainer;
import net.minecraft.server.v1_7_R4.TileEntity;
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_7_R4.World world = ((CraftWorld) Bukkit.getWorlds().get(0)).getHandle();
for (Location location : blocksForUpdate) {
world.notify(location.getBlockX(), location.getBlockY(), location.getBlockZ());
}
blocksForUpdate.clear();
}
}
}.runTaskTimer(Utils.getPlugin(Utils.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_7_R4.World w = ((CraftWorld) world).getHandle();
net.minecraft.server.v1_7_R4.Chunk chunk = w.getChunkAt(x >> 4, z >> 4);
boolean b = data(chunk, x & 0x0f, y, z & 0x0f, net.minecraft.server.v1_7_R4.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_7_R4.Chunk that, int i, int j, int k, net.minecraft.server.v1_7_R4.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_7_R4.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_7_R4.ChunkSection chunksection = that.getSections()[j >> 4];
if (chunksection == null) {
if (block == net.minecraft.server.v1_7_R4.Blocks.AIR) {
return false;
}
chunksection = that.getSections()[j >> 4] = new net.minecraft.server.v1_7_R4.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);
}
}
}

Related

how can I sort the class generic type when read from file with

I have this class and I read from file the data and my program is add the word and I count every word for example:
(WData{word=success, count=1} WData{word=automata, count=1} Data{word=theory, count=2}) How can I sort the output and start with character A to Z I mean the word and. this my code
Class Sa
class SA:
public class SA<T> {
int head;
int size;
T[] nodes;
public SA(int maxsize) {
head = 0;
nodes = (T[]) new Object[maxsize];
size = 0;
}
public int size() {
return size;}
public boolean empty() {
return size == 0;
public void insert(T e) {
nodes[size] = e;
size++;
}
public T find(T s) {
if (size != 0) {
for (int i = 0; i < size; i++) {
if (nodes[i].equals(s)) {
return nodes[i];
}
}
}
return null;
}
public void display() {
for (int i = 0; i < size; i++) {
System.out.println(nodes[i].toString());
}}}
and here class TextAnalyzer:
Public class TextAnalyzer<T> {
private static class WData {
#Override
public int hashCode() {
int hash = 7;
hash = 71 * hash + Objects.hashCode(this.word);
return hash;
}
#Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final WData other = (WData) obj;
if (!Objects.equals(this.word, other.word)) {
return false;
}
return true;
}
String word;
int count;
public WData(String w, int f) {
word = w;
count = f;
}
#Override
public String toString() {
return "WData{" + "word=" + word + ", count=" + count + '}';
}
} SA<WData>list;
public TextAnalyzer() {
list=new SA<WData>(11000);
}
public void processText(String filename) {
long count = 0;
try {
Scanner sc = new Scanner(new File(filename));;
while (sc.hasNext()) {
String line = sc.next();
String st = line.replaceAll("[^a-zA-Z ]", "").toLowerCase();
processWord(st);}
list.display();
} catch (FileNotFoundException ex) {
System.out.println("There are error in processText");
}
}
public void processWord(String word) {
WData w = new WData(word, 1);
WData s = list.find(w);
if (s == null) {
list.insert(w);
} else {
s.count = s.count + 1;
}}}

Minecraft Forge - Container slots offset?

I am creating a new mod that has a container. The issue is that the inventory slots are offset by 7. It seems like the server thinks the first column is where the second-to-last column, and the second column is where the last column is. Here is some code. The classes should be included.
public class GuiHandler implements IGuiHandler {
public Object getServerGuiElement(int ID, EntityPlayer player, World world, int x, int y, int z) {
if (ID == 0) {
return new ContainerGenerator(player.inventory, (TileEntityGenerator) world.getTileEntity(x, y, z));
} else {
return null;
}
}
public Object getClientGuiElement(int ID, EntityPlayer player, World world, int x, int y, int z) {
if (ID == 0) {
return new GuiGenerator(player.inventory, (TileEntityGenerator) world.getTileEntity(x, y, z));
} else {
return null;
}
}
}
The container class
public class ContainerGenerator extends Container {
private TileEntityGenerator tileEntity;
private int count;
public ContainerGenerator(InventoryPlayer inventory, TileEntityGenerator tileEntity) {
this.tileEntity = tileEntity;
this.tileEntity.openInventory();
this.count = tileEntity.getCount();
this.addSlotToContainer(new Slot(tileEntity, 0, 27, 47));
this.addSlotToContainer(new Slot(tileEntity, 1, 134, 47));
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 9; j++) {
this.addSlotToContainer(new Slot(inventory, j + i * 9 + 9, 8 + j * 18, 84 + i * 18));
}
}
for (int i = 0; i < 9; i++) {
this.addSlotToContainer(new Slot(inventory, i, 8 + i * 18, 142));
}
}
// some other random code
And some relevent tile entity overrides (there is some other random code)
#Override
public void readFromNBT(NBTTagCompound nbt) {
super.readFromNBT(nbt);
this.count = nbt.getInteger("count");
NBTTagList tagList = nbt.getTagList("items", 10);
this.items = new ItemStack[2];
NBTTagCompound compound = tagList.getCompoundTagAt(0);
byte slotId = compound.getByte("slot");
if (slotId >= 0 && slotId < 2) {
items[slotId] = ItemStack.loadItemStackFromNBT(compound);
}
compound = tagList.getCompoundTagAt(1);
slotId = compound.getByte("slot");
if (slotId >= 0 && slotId < 2) {
items[slotId] = ItemStack.loadItemStackFromNBT(compound);
}
}
#Override
public void writeToNBT(NBTTagCompound nbt) {
super.writeToNBT(nbt);
nbt.setInteger("count", count);
NBTTagList list = new NBTTagList();
if (items[0] != null) {
NBTTagCompound compound = new NBTTagCompound();
compound.setByte("slot", (byte) 0);
items[0].writeToNBT(compound);
list.appendTag(compound);
}
if (items[1] != null) {
NBTTagCompound compound = new NBTTagCompound();
compound.setByte("slot", (byte) 1);
items[1].writeToNBT(compound);
list.appendTag(compound);
}
nbt.setTag("items", list);
}
#Override
public int getSizeInventory() {
return items.length;
}
#Override
public ItemStack getStackInSlot(int slot) {
return items[slot];
}
#Override
public ItemStack decrStackSize(int slot, int amount) {
if (items[slot] == null) {
return null;
}
if (items[slot].stackSize == amount) {
ItemStack itemStack = items[slot];
items[slot] = null;
return itemStack;
} else {
ItemStack itemStack = items[slot].splitStack(amount);
if (items[slot].stackSize == 0) {
items[slot] = null;
}
markDirty();
return itemStack;
}
}
#Override
public ItemStack getStackInSlotOnClosing(int slot) {
if (items[slot] != null) {
ItemStack itemStack = items[slot];
items[slot] = null;
return itemStack;
} else {
return null;
}
}
#Override
public void setInventorySlotContents(int slot, ItemStack stack) {
items[slot] = stack;
if (stack != null && stack.stackSize > getInventoryStackLimit()) {
markDirty();
}
}
Edit: screenshots. Notice which slots are highlighted if any.
Sorry for the lengthy post. I'm new to modding, so it is hard for me to pin point the issue exactly.

Print a Binary Search Tree with Correct Formatting

I have a binary tree program that sorts smaller/equal numbers to the left of the parent, and larger numbers to the right of the parent, and I want to print out a diagram of it, but I don't know how to print it so it formats well. Also, should the print method be part of the TreeDriver class, or part of the TreeNode class to recursively access every node.
Here are the classes:
TreeDriver:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
/**
* This class serves as the driver for a generic TreeNode, giving it the type of Integer.
*/
public class TreeDriver
{
//region Instance Variables
TreeNode<Integer> root;
//endregion
//region Constructors
public TreeDriver() throws FileNotFoundException
{
fill();
System.out.println("Count: " + root.getCount());
}
//endregion
//region Public Methods
public void fill() throws FileNotFoundException
{
Scanner reader = new Scanner(new File("TreeValueSource"));
String temp;
Integer entry;
makeRoot();
while (reader.hasNext())
{
temp = reader.nextLine();
if (temp.contains("//"))
{
if (reader.hasNext())
temp = reader.nextLine();
else break;
}
else if (checkInt(temp))
{
entry = new Integer(temp);
root.add(entry);
}
else System.out.println("ERROR IN FILL");
}
}
private void makeRoot()
{
Scanner scan = new Scanner(System.in);
System.out.println("Enter a root value(default 50): ");
String input = scan.next();
if (checkInt(input))
root = new TreeNode<>(new Integer(input));
else
root = new TreeNode<>(50);
}
public void printCount()
{
System.out.println(root.getCount());
}
//endregion
//region Private Methods
private boolean checkInt(String candidate)
{
boolean parsable = true;
try
{
Integer.parseInt(candidate);
} catch (NumberFormatException e)
{
parsable = false;
}
return parsable;
}
//endregion
}
TreeNode:
public class TreeNode<T extends Comparable<T>>
{
//region Instance Variables
//Links
private TreeNode<T> leftChild; //Left Link
private TreeNode<T> rightChild; //Right Link
//Properties
private T data; //Info Stored by the TreeNode
private int childCount; //Number of Children
private int depth; //Level of the Node in the Tree
//endregion
//region Constructors
public TreeNode(T data, int parentDepth)
{
leftChild = null;
rightChild = null;
childCount = 0;
depth = parentDepth + 1;
this.data = data;
}
public TreeNode(T data)
{
leftChild = null;
rightChild = null;
childCount = 0;
depth = 0;
this.data = data;
System.out.println("A Root was Created");
}
//endregion
//region Public Methods
/**
* ADD
* Adds a new TreeNode to the tree. Left if equal or smaller, Right if larger
*
* #param data The data held by the TreeNode
* #see TreeNode
*/
public void add(T data)
{
if (this.data.compareTo(data) <= 0)
{
addLeft(data);
} else if (this.data.compareTo(data) > 0)
{
addRight(data);
} else
{
System.out.println("ERROR IN TREENODE.ADD");
}
}
public int getCount()
{
return count();
}
/**
* IS LEAF
* Determines if the current node has no children
*
* #return True if no children, False otherwise
*/
public boolean isLeaf()
{
return childCount == 0;
}
//endregion
//region Private Methods
//Adds the data to the left of this.TreeNode
private void addLeft(T data)
{
if (null == leftChild)
{
leftChild = new TreeNode(data, depth);
childCount += 1;
} else
leftChild.add(data);
}
//Adds the data to the right of this.TreeNode
private void addRight(T data)
{
if (null == rightChild)
{
rightChild = new TreeNode(data, depth);
childCount += 1;
} else
rightChild.add(data);
}
/**
* COUNT
* Recursively counts the number of TreeNodes
*
* #return the number of TreeNodes, 0 if an error
*/
private int count()
{
if (isLeaf())
{
return 1;
} else if (childCount == 2)
{
return 1 + leftChild.count() + rightChild.count();
} else if (null == leftChild)
{
return 1 + rightChild.count();
} else if (null == rightChild)
{
return 1 + leftChild.count();
} else
{
System.out.println("ERROR IN COUNT AT DEPTH " + depth);
return 0;
}
}
//endregion
}
You can use this answer as a model
[How to print binary tree diagram?
Modifying the BtreePrinter Class. And no you shouldn't put the print method in the TreeDriver class.
class Node<T extends Comparable<?>> {
Node<T> left, right;
T data;
public Node(T data) {
this.data = data;
}
}
class BTreePrinter {
public static <T extends Comparable<?>> void printNode(Node<T> root) {
int maxLevel = BTreePrinter.maxLevel(root);
printNodeInternal(Collections.singletonList(root), 1, maxLevel);
}
private static <T extends Comparable<?>> void printNodeInternal(List<Node<T>> nodes, int level, int maxLevel) {
if (nodes.isEmpty() || BTreePrinter.isAllElementsNull(nodes))
return;
int floor = maxLevel - level;
int endgeLines = (int) Math.pow(2, (Math.max(floor - 1, 0)));
int firstSpaces = (int) Math.pow(2, (floor)) - 1;
int betweenSpaces = (int) Math.pow(2, (floor + 1)) - 1;
BTreePrinter.printWhitespaces(firstSpaces);
List<Node<T>> newNodes = new ArrayList<Node<T>>();
for (Node<T> node : nodes) {
if (node != null) {
System.out.print(node.data);
newNodes.add(node.left);
newNodes.add(node.right);
} else {
newNodes.add(null);
newNodes.add(null);
System.out.print(" ");
}
BTreePrinter.printWhitespaces(betweenSpaces);
}
System.out.println("");
for (int i = 1; i <= endgeLines; i++) {
for (int j = 0; j < nodes.size(); j++) {
BTreePrinter.printWhitespaces(firstSpaces - i);
if (nodes.get(j) == null) {
BTreePrinter.printWhitespaces(endgeLines + endgeLines + i + 1);
continue;
}
if (nodes.get(j).left != null)
System.out.print("/");
else
BTreePrinter.printWhitespaces(1);
BTreePrinter.printWhitespaces(i + i - 1);
if (nodes.get(j).right != null)
System.out.print("\\");
else
BTreePrinter.printWhitespaces(1);
BTreePrinter.printWhitespaces(endgeLines + endgeLines - i);
}
System.out.println("");
}
printNodeInternal(newNodes, level + 1, maxLevel);
}
private static void printWhitespaces(int count) {
for (int i = 0; i < count; i++)
System.out.print(" ");
}
private static <T extends Comparable<?>> int maxLevel(Node<T> node) {
if (node == null)
return 0;
return Math.max(BTreePrinter.maxLevel(node.left), BTreePrinter.maxLevel(node.right)) + 1;
}
private static <T> boolean isAllElementsNull(List<T> list) {
for (Object object : list) {
if (object != null)
return false;
}
return true;
}
}

Java AI find solution for NxN Puzzle

First of all there is a lot of code because i really don't know where my issue is, I do apologise!
I'm making a program that solves a varying size puzzle for eg (3x3 with 0-8) The zero represents a blank tile the objective is to move the the blank tile around until the goal state is reached. At the moment I am using Depth First Search to solve the puzzle. Netbeans returns a 'OutOfMemory' error when i run the program however if I change the goal state so it only requires one move to complete it displays the solution. Below is my code, I've only added some of the classes because I don't want this post being ridiculously long. Please let me know if you require the other classes
EDIT: Inserted wrong code for board class
Depth First Search Class
package npuzzle;
import java.util.ArrayList;
import java.util.Stack;
public class DFSearch {
public static void search(int[][] initial, int[][] goal, int rows, int columns)
{
Board board = new Board(initial, goal, rows, columns, "");
Node root = new Node(board);
Stack<Node> stack = new Stack<Node>();
stack.add(root);
performSearch(stack, board);
}
public static void performSearch(Stack<Node> s, Board board)
{
int searchCount = 1;
while (!s.isEmpty())
{
Node tNode = (Node) s.pop();
//if not goal state
if (!tNode.getCurrentState().isGoalState())
{
ArrayList<State> tChildren = tNode.getCurrentState().gChildren();
for (int i = 0; i < tChildren.size(); i++)
{
Node newNode = new Node(tNode, tChildren.get(i), tNode.getGCost() + tChildren.get(i).findCost(), 0);
if(!isRepeatedState(newNode))
{
s.add(newNode);
}
}
searchCount++;
}
else
{
tNode.getCurrentState().printState();
System.exit(0);
//PRINTING OF DIRECTIONS
}
}
System.out.println("Error! No solution found!");
}
private static boolean isRepeatedState(Node c)
{
boolean returnVal = false;
Node checkNode = c;
while(c.getParent() != null && !returnVal)
{
if (c.getParent().getCurrentState().equals(checkNode.getCurrentState()))
{
returnVal = true;
}
c = c.getParent();
}
return returnVal;
}
}
Board Class
package npuzzle;
import java.util.ArrayList;
import java.util.Arrays;
public class Board implements State
{
private int PUZZLE_SIZE = 0;
private int outOfPlace = 0;
private int rows;
private int columns;
private int[][] GOAL;
private int[][] currentBoard;
private String directions = "";
public Board(int[][] initial, int[][] goal, int N, int M, String direction)
{
currentBoard = initial;
GOAL = goal;
rows = N;
columns = M;
PUZZLE_SIZE = rows*columns;
directions = direction;
setOutOfPlace();
}
#Override
public boolean isGoalState() {
if (Arrays.deepEquals(currentBoard, GOAL))
{
return true;
}
return false;
}
#Override
public ArrayList<State> gChildren() {
ArrayList<State> children = new ArrayList<State>();
int[] blanktile = getBlankTile();
int[] newblanktile = Arrays.copyOf(blanktile, blanktile.length);
if (blanktile[0] != 0) {
newblanktile[0]--;
Swap(newblanktile, blanktile, children, "up");
newblanktile = Arrays.copyOf(blanktile, blanktile.length);
}
if (blanktile[1] != 0) {
newblanktile[1]--;
Swap(newblanktile, blanktile, children, "left");
newblanktile = Arrays.copyOf(blanktile, blanktile.length);
}
if (blanktile[0] != (this.rows - 1)) {
newblanktile[0]++;
Swap(newblanktile, blanktile, children, "down");
newblanktile = Arrays.copyOf(blanktile, blanktile.length);
}
if (blanktile[1] != (this.columns - 1)) {
newblanktile[1]++;
Swap(newblanktile, blanktile, children, "right");
newblanktile = Arrays.copyOf(blanktile, blanktile.length);
}
return children;
}
#Override
public double findCost() {
return 1;
}
#Override
public void printState() {
System.out.println(directions);
}
#Override
public boolean equals(State s) {
if (Arrays.deepEquals(currentBoard, ((Board) s).getCurrentBoard()))
{
return true;
}
else
return false;
}
private void setOutOfPlace() {
int i = 0;
int j = -1;
do
{
if (j == (columns - 1)) {j = 0; i++;}
else {j++;}
if (currentBoard[i][j] != GOAL[i][j])
{
outOfPlace++;
}
} while (((i+1)*(j+1)) < PUZZLE_SIZE);
}
private int[] getBlankTile()
{
int i = 0;
int j = -1;
int[] blanktile = {0,0};
do
{
if (j == (columns - 1)) {j = 0; i++;}
else {j++;}
if (currentBoard[i][j] == 0) {
blanktile[0] = i;
blanktile[1] = j;
}
} while (((i+1)*(j+1)) < PUZZLE_SIZE);
return blanktile;
}
public int getOutOfPlace()
{
return outOfPlace;
}
private int[][] copyBoard(int[][] state)
{
int[][] returnArray = new int[rows][columns];
for (int i = 0, j = 0; i*j < PUZZLE_SIZE; i++, j++)
{
returnArray[i] = Arrays.copyOf(state[i], state[i].length);
}
return returnArray;
}
private void Swap(int[] nbt, int[] bt, ArrayList<State> children, String direction) {
int[][] cpy = copyBoard(currentBoard);
int temp = cpy[nbt[0]][nbt[1]];
cpy[nbt[0]][nbt[1]] = currentBoard[bt[0]][bt[1]];
cpy[bt[0]][bt[1]] = temp;
children.add(new Board(cpy, this.getGOAL(), this.getRows(), this.getColumns(), (this.getDirections() + direction + ", ")));
}
public int getPUZZLE_SIZE() {
return PUZZLE_SIZE;
}
public int getRows() {
return rows;
}
public int getColumns() {
return columns;
}
public int[][] getGOAL() {
return GOAL;
}
public int[][] getCurrentBoard()
{
return currentBoard;
}
public String getDirections()
{
return directions;
}
}

I call a method and it gives me an error

My source code:
import java.util.*;
public class Arvore {
public Arvore() {
root = null;
}
public void inserir(String x) {
root = insert(x, root);
}
public void remove(String x) {
root = remove(x, root);
}
private No remove(String x, No t) {
if (t == null) {
return t;
}
int comp = x.compareTo(t.str);
if (comp < 0) {
t.left = remove(x, t.left);
} else if (comp > 0) {
t.right = remove(x, t.right);
} else if (t.left != null && t.right != null) {
t.str = findMin(t.right).str;
t.right = remove(t.str, t.right);
} else {
t = (t.left != null) ? t.left : t.right;
}
return balance(t);
}
public String findMin() {
return findMin(root).str;
}
public String findMax() {
return findMax(root).str;
}
public boolean contains(String x) {
return contains(x, root);
}
public void makeEmpty() {
root = null;
}
public boolean isEmpty() {
return root == null;
}
private static final int maxBal = 1;
private No balance(No t) {
if (t == null) {
return t;
}
if (height(t.left) - height(t.right) > maxBal) {
if (height(t.left.left) >= height(t.left.right)) {
t = rotateWithLeftChild(t);
} else {
t = doubleWithLeftChild(t);
}
} else if (height(t.right) - height(t.left) > maxBal) {
if (height(t.right.right) >= height(t.right.left)) {
t = rotateWithRightChild(t);
} else {
t = doubleWithRightChild(t);
}
}
t.height = Math.max(height(t.left), height(t.right)) + 1;
return t;
}
public void checkBalance() {
checkBalance(root);
}
private int checkBalance(No t) {
if (t == null) {
return -1;
}
if (t != null) {
int hl = checkBalance(t.left);
int hr = checkBalance(t.right);
if (Math.abs(height(t.left) - height(t.right)) > 1
|| height(t.left) != hl || height(t.right) != hr) {
System.out.println("OOPS!!");
}
}
return height(t);
}
private No insert(String x, No t) {
if (t == null) {
return new No(x, null, null);
}
int comp = x.compareTo(t.str);
if (comp < 0) {
t.left = insert(x, t.left);
} else if (comp > 0) {
t.right = insert(x, t.right);
} else
;
t.occ+=1;
return balance(t);
}
private No findMin(No t) {
if (t == null) {
return t;
}
while (t.left != null) {
t = t.left;
}
return t;
}
private No findMax(No t) {
if (t == null) {
return t;
}
while (t.right != null) {
t = t.right;
}
return t;
}
private boolean contains(String x, No t) {
while (t != null) {
int comp = x.compareTo(t.str);
if (comp < 0) {
t = t.left;
} else if (comp > 0) {
t = t.right;
} else {
return true;
}
}
return false;
}
private void printTree(No t) {
if (t != null) {
printTree(t.left);
System.out.println(t.str + ": " + t.occ);
printTree(t.right);
}
}
private int height(No t) {
return t == null ? -1 : t.height;
}
private No rotateWithLeftChild(No k2) {
No k1 = k2.left;
k2.left = k1.right;
k1.right = k2;
k2.height = Math.max(height(k2.left), height(k2.right)) + 1;
k1.height = Math.max(height(k1.left), k2.height) + 1;
return k1;
}
private No rotateWithRightChild(No k1) {
No k2 = k1.right;
k1.right = k2.left;
k2.left = k1;
k1.height = Math.max(height(k1.left), height(k1.right)) + 1;
k2.height = Math.max(height(k2.right), k1.height) + 1;
return k2;
}
private No doubleWithLeftChild(No k3) {
k3.left = rotateWithRightChild(k3.left);
return rotateWithLeftChild(k3);
}
private No doubleWithRightChild(No k1) {
k1.right = rotateWithLeftChild(k1.right);
return rotateWithRightChild(k1);
}
private class No {
No(String tStr) {
this(tStr, null, null);
}
No(String tStr, No lt, No rt) {
str = tStr;
left = lt;
right = rt;
height = 0;
occ = 1;
}
String str;
No left;
No right;
int height;
int occ = 0;
}
private No root;
public static void main(String[] args) {
Arvore t = new Arvore();
System.out.println("AVL TREE TEST\n");
String msg;
String[] inputs;
Scanner sc = new Scanner(System.in);
ArrayList palavras = new ArrayList();
int i = 0;
while (true) {
msg = sc.nextLine();
if (msg.equals("")) {
break;
}
inputs = msg.split(" ");
i = 0;
while (i < inputs.length) {
palavras.add(inputs[i]);
}
}
i = 0;
while (i < palavras.size()) {
if (palavras.get(i).equals("REMOVE")) {
palavras.remove(palavras.get(i));
palavras.remove(palavras.get(i + 1));
i += 2;
} else {
t.insert(palavras.get(i));
}
i++;
}
t.printTree();
}
}
I can't figure out why i have an error when i call insert and printTree, on the main function.
And i have a warning by adding a string to my arraylist, when i do palavras.add(inputs[i]).
Your loop:
i = 0;
while (i < inputs.length) {
palavras.add(inputs[i]);
}
is not incrementing i, so you will eventually run out of space for the array as you try to insert an infinite number of references to inputs[0].
The warning is because you are using a raw ArrayList. Try declaring palavras as:
ArrayList<String> palavras = new ArrayList<>(); // new ArrayList<String>(); if pre Java 7
Your other loop:
i = 0;
while (i < palavras.size()) {
if (palavras.get(i).equals("REMOVE")) {
palavras.remove(palavras.get(i));
palavras.remove(palavras.get(i + 1));
i += 2;
} else {
t.insert(palavras.get(i));
}
i++;
}
will generate an IndexOutOfBoundsException if the first branch of the if is taken when i == palavras.size() - 1 when it tries to remove the second element. Even if you are guaranteed that "REMOVE" is always followed by another element, you need to either reverse the order of the removals:
palavras.remove(palavras.get(i + 1));
palavras.remove(palavras.get(i));
or remove the element at i twice:
palavras.remove(palavras.get(i));
palavras.remove(palavras.get(i));
(because when you call remove() it moves all succeeding elements down one position in the array).
You are calling t.printTree() but, there is no such method defined in class Arvore; the method you did define takes a tree as an argument. Same thing with insert(): the actual method that's available takes a String and a No as arguments.

Categories

Resources