I'm not sure what this error is or why it is happening. verything I've found online has nothing to do with TableViews. But when this method in my prisoner Class is accessed by my TableView it throws a InvocationTargetException. This is my first time using a TableView.
public int getCellBlock() {
for (int i = 0; i < Main.getCellBlocks().size(); i++) //for each cellblock
for (int j = 0; j < Main.getCellBlocks().get(i).getCells().size(); j++) //for each cell
for (int k = 0; k < Main.getCellBlocks().get(i).getCells().get(j).getInmates().size(); k++)
if (Main.getCellBlocks().get(i).getCells().get(j).getInmates().get(k).equals(this.idNum)) {
return i;
}
return -1;
}
Cell (has two subclasses but im not accessing data in them with the above method):
import java.io.Serializable;
import java.util.ArrayList;
public class Cell implements Serializable {
private ArrayList<Integer> inmateIdNums;
private int capacity = 0;
Cell(int cap){
capacity = cap;
inmateIdNums = new ArrayList<>();
for (int i = 0; i < capacity; i++)
inmateIdNums.add(null);
}
public void add (int idNum){
for (int i = 0; i < capacity; i++){
if (inmateIdNums.get(i) == null) {
inmateIdNums.set(i, idNum);
break;
}
}
}
public void add (int idNum, int dur){}
public void add (int idNum, String reason){}
public ArrayList<Integer> getInmates(){ return inmateIdNums; }
public int getEmptyBunks(){
int emptyBunks = 0;
for (int i = 0; i < inmateIdNums.size(); i++){
if (inmateIdNums.get(i) == null)
emptyBunks++;
}
return emptyBunks;
}
}
CellBlock:
import java.io.Serializable;
import java.util.ArrayList;
public class CellBlock implements Serializable{
private String name;
private String type;
private int capacity;
private int occupancy = 0;
private ArrayList<Cell> cells;
CellBlock(int cap, String nName, String nType, int cellCapacity){
name = nName;
type = nType;
capacity = cap;
cells = new ArrayList<>(capacity);
if (type == "Maximum Security" || type == "Minimum Security") {
for (int i = 0; i < capacity; i++)
cells.add(new Cell(cellCapacity));
}
else if(type == "Infirmary"){
for (int i = 0; i < capacity; i++)
cells.add(new InfirmaryCell(cellCapacity));
}
else if(type == "Isolation"){
for (int i = 0; i < capacity; i++)
cells.add(new IsolationCell(cellCapacity));
}
}
public void addInmate(int cell, int inmateIdNum){
cells.get(cell-1).add(inmateIdNum);
occupancy++;
}
public void addInmate(int cell, int inmateIdNum, String reason){
cells.get(cell-1).add(inmateIdNum, reason);
occupancy++;
}
public void addInmate(int cell, int inmateIdNum, int duration){
cells.get(cell-1).add(inmateIdNum, duration);
occupancy++;
}
public void removeInmate(int inmateIdNum){
//search for inmate and remove from list
}
public ArrayList<Cell> getInmates(){ return cells; }
public boolean checkCapacity(){
if (capacity > occupancy)
return true;
return false;
}
public ArrayList<Cell> getCells(){ return cells; }
public ArrayList<String> getOpenCells(){
ArrayList<String> openCells = new ArrayList<>();
for (int i = 0; i < cells.size();i++){
if (cells.get(i).getEmptyBunks() > 0)
openCells.add(Integer.toString(i+1));
}
return openCells;
}
}
The Error:
I'm not sure which did it, but I fixed this myself. The loops were fine.
The problem was one of two things - the comparison, or the files where I had written the information (I am using binary files and ObjectInputStream/ObjectOutputStream).
In the Cell constructor I had:
for (int i = 0; i < capacity; i++)
inmateIdNums.add(null);
And to avoid comparing Integer to null I changed it to:
for (int i = 0; i < capacity; i++)
inmateIdNums.add(0);
This did not fix my issue. So I could only assume that someone where along the way something went wrong with one of my files being written while this crappy comparison was going on. As a last ditch effort I deleted the files I had been working with and ran my program fresh to create new files and add new entries.
Problem solved.
Related
I am following an online example and learning "Circular Deque implementation in Java using array". Here is the online resource that I am following:
Circular Queue Implementation
I have an array based deque class which has final capacity of 5. Now if the array is full then I can have the methods create a temporary array of all the objects and then copy all the objects of temporary array back to "object[] arr". I have been at it for some time now but have not been able to get it going. I would appreciate if someone can help me understand the process here please. I have following class methods:
insertAtFront()
insertAtLast()
size()
isEmpty()
toString()
Here is my code:
public class ArrayDeque {
private static final int INIT_CAPACITY = 5;
private int front;
private int rear;
private Object[] arr;
public ArrayDeque(){
arr = new Object[ INIT_CAPACITY ];
front = 0;
rear = 0;
}
public void insertAtFirst(Object item){
if(size() >= arr.length){
Object[] tmp = new Object[arr.length + INIT_CAPACITY];
for(int i = 0; i < size(); ++i)
tmp[i] = arr[i];
arr = tmp;
}
arr[front] = item;
++front;
}
public void insertAtLast(Object item){
if(size() >= arr.length){
Object[] tmp = new Object[arr.length + INIT_CAPACITY];
for(int i = 0; i < size(); ++i)
tmp[i] = arr[i];
arr = tmp;
}
arr[rear] = item;
++rear;
}
public int size(){
return (rear - front);
}
public boolean isEmpty(){
return (front == rear);
}
public String toString(){
String s = "";
for(int i = 0; i < size(); ++i)
s += arr[i] + "\n";
return s;
}
}//CLASS
Try the below code, i changed the logic a bit by keeping track of how much the array is filled up. Your main problem is with the size() function, which is giving wrong indications. Some optimization is pending for i see some nulls in the results.
public class ArrayDeque {
public static void main(String[] args) {
ArrayDeque t = new ArrayDeque ();
t.insertAtFirst("1");
t.insertAtFirst("2");
t.insertAtFirst("3");
t.insertAtFirst("4");
t.insertAtFirst("5");
t.insertAtFirst("6");
t.insertAtFirst("7");
t.insertAtFirst("8");
t.insertAtFirst("9");
t.insertAtFirst("10");
t.insertAtFirst("11");
t.insertAtFirst("12");
t.insertAtFirst("13");
t.insertAtFirst("14");
System.out.println("After first--"+t.toString());
t.insertAtLast("1");
t.insertAtLast("2");
t.insertAtLast("3");
t.insertAtLast("4");
t.insertAtLast("5");
t.insertAtLast("6");
t.insertAtLast("7");
t.insertAtLast("8");
t.insertAtLast("9");
t.insertAtLast("10");
t.insertAtLast("11");
t.insertAtLast("12");
t.insertAtLast("13");
t.insertAtLast("14");
System.out.println("After last--"+t.toString());
}
private static final int INIT_CAPACITY = 5;
private int NEW_CAPACITY;
private int ARRAY_SIZE;
private Object[] arr;
public TestClass(){
arr = new Object[ INIT_CAPACITY ];
NEW_CAPACITY = INIT_CAPACITY;
ARRAY_SIZE = 0;
}
public void insertAtFirst(Object item){
if(ARRAY_SIZE == 0)
{
arr[0] = item;
ARRAY_SIZE++;
}
else if(ARRAY_SIZE+1 < arr.length)
{
Object[] tmp = new Object[NEW_CAPACITY];
for(int i = 1; i < arr.length; ++i)
tmp[i] = (String)arr[i-1];
arr = tmp;
arr[0] = item;
ARRAY_SIZE++;
}
else if(ARRAY_SIZE+1 >= arr.length)
{
NEW_CAPACITY = NEW_CAPACITY+INIT_CAPACITY;
Object[] tmp = new Object[NEW_CAPACITY];
for(int i = 1; i < arr.length; ++i)
tmp[i] = (String)arr[i-1];
arr = tmp;
arr[0] = item;
ARRAY_SIZE++;
}
}
public void insertAtLast(Object item){
if(ARRAY_SIZE == 0)
{
arr[0] = item;
ARRAY_SIZE++;
}
else if(ARRAY_SIZE+1 < arr.length)
{
arr[ARRAY_SIZE] = item;
ARRAY_SIZE++;
}
else if(ARRAY_SIZE+1 >= arr.length)
{
NEW_CAPACITY = NEW_CAPACITY+INIT_CAPACITY;
Object[] tmp = new Object[NEW_CAPACITY];
for(int i = 0; i < arr.length; ++i)
tmp[i] = (String)arr[i];
arr = tmp;
arr[ARRAY_SIZE] = item;
ARRAY_SIZE++;
}
}
public int size(){
return ARRAY_SIZE;
}
public boolean isEmpty(){
return (ARRAY_SIZE == 0);
}
public String toString(){
String s = "";
for(int i = 0; i < arr.length; ++i)
s += arr[i] + "\t";
return s;
}
}
This question already has answers here:
Type Cannot create a generic array of List<FooClass>
(3 answers)
"Cannot create generic array of .." - how to create an Array of Map<String, Object>?
(6 answers)
Closed 1 year ago.
Here is the code I have that works but with a type safety warning when I size and instantiate the array:
import java.util.ArrayList;
import java.util.List;
public class Test {
private static final int MAX_ROWS = 2;
private static final int MAX_COLS = 5;
private List<String> _stringSets[][];
public Test() {
_stringSets = new List[MAX_ROWS][MAX_COLS];
for(int row = 0; row < MAX_ROWS; row++) {
for(int col = 0; col < MAX_COLS; col++) {
_stringSets[row][col] = new ArrayList<String>();
}
}
}
}
I tried
_stringSets = new List<String>[MAX_ROWS][MAX_COLS];
but this won't work...
Lists are unidimensional and would be declared something like this:
List<String> myList = new ArrayList<>()
When you seem to be looking for a 2-dimensional arrays, which are declared something like this:
String[][] myArray = new String[n1][n2]
So what you want is probably something along those lines:
public class Test {
private static final int MAX_ROWS = 2;
private static final int MAX_COLS = 5;
private String[][] stringSets;
public Test() {
stringSets = new String[MAX_ROWS][MAX_COLS];
for(int row = 0; row < MAX_ROWS; row++) {
for(int col = 0; col < MAX_COLS; col++) {
stringSets[row][col] = row+"-"+col;
}
}
}
}
Generally not recommended to mix Arrays and Lists in this way. May want to consider using other data structures to achieve a similar effect instead. For example, you could create a Map that uses Position coordinates to achieve similar results.
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
public class MapList {
private static Map<Position, List<Integer>> mapList;
public static void main(String[] args) {
final int MAX_X = 5;
final int MAX_Y = 6;
mapList = new HashMap<>();
for(int i = 0; i < MAX_X; i++) {
for(int j = 0; j < MAX_Y; j++) {
mapList.put(new Position(i, j), new ArrayList<>());
for(int k = 0; k < 5; k++) {
mapList.get(new Position(i, j)).add(k);
}
}
}
for(Position p : mapList.keySet())
System.out.println(p.toString() + mapList.get(p));
}
private static class Position {
private Integer x;
private Integer y;
public Position(Integer x, Integer y) {
this.x = x;
this.y = y;
}
#Override
public boolean equals(Object o) {
if(this == o)
return true;
if(o == null)
return false;
if(getClass() != o.getClass())
return false;
Position other = (Position) o;
return x == other.x && y == other.y;
}
#Override
public int hashCode() {
return Objects.hash(x, y);
}
#Override
public String toString() {
return "(x:" + x + ", y:" + y + ")";
}
}
}
This is my Arraylist I'm having trouble how to make a new class to check if my methods work.
Any help will be useful I need to know how to make a start my new class .
I create a class but I keep getting it wrong.
Do I have to extend it our in my new class am only?
Any assistance will be greatly useful.
public class MyArray<E extends Comparable<E>> {
// No other data fields necessary.
private E[] data;
private int size;
public MyArray(int size) {
this.data = (E[]) (new Comparable[size]);
size = 0;
}
public void add(E item) {
if (size == data.length)
resize();
data[size] = item;
size++;
}
private void resize() {
int len = data.length * 2;
E[] temp = (E[]) new Comparable[len];
for (int i = 0; i < size; i++)
temp[i] = data[i];
data = temp;
}
public boolean contains(E item) {
for (int i = 0; i < size; i++) {
if (data[i].equals(item))
return true;
}
return false; // not found
}
public void delete(int index) {
if (index < 0 || index >= size)
throw new IndexOutOfBoundsException();
for (int i = index + 1; i < size; i++) {
data[i - 1] = data[i];
}
size--;
}
public boolean delete(E item) {
if (item == null)
return false;
for (int i = 0; i < size; i++) {
if (data[i].equals(item)) {
delete(i); // delete at index i
return true;
}
}
return false;// not found
}
}
Since your class is defined with generics (the E), you have to provide an actual type for E. Actually, it should work pretty much like ArrayList class.
MyArray<String> a = new MyArray<String>(10);
a.add("Foo");
a.add("Bar");
I have a jagged array.
How can I override next(), so I can get its elements step-by-step?
This might be a wrong answer to your question. I'll remove it in that case, but maybe you can use it for what you want to achieve:
int[][] it = {{1,2}, {3,4,5}};
OfInt iterator = Arrays.stream(it).flatMapToInt(x -> IntStream.of(x)).iterator();
iterator.forEachRemaining((IntConsumer) System.out::print);
Stream the jagged array, flatmap it into one single IntStream and then do what you want with it. In this example I fetched the iterator but you might only want:
Arrays.stream(it).flatMapToInt(x -> IntStream.of(x)).forEach((IntConsumer) System.out::print);
In forEach you can do what you need, or use some other method of IntStream
Thank you all for your answers, I've found my answer in russian stackoverflow:
https://ru.stackoverflow.com/questions/867881/java-iterator-%D0%B4%D0%BB%D1%8F-%D0%BC%D0%BD%D0%BE%D0%B3%D0%BE%D0%BC%D0%B5%D1%80%D0%BD%D0%BE%D0%B3%D0%BE-%D0%BC%D0%B0%D1%81%D1%81%D0%B8%D0%B2%D0%B0
public class IteratorFor2DArray implements Iterator {
private int size;
private int i = 0;
private int j = 0;
private int[][] values = new int[i][j];
private int position = 0;
public IteratorFor2DArray(int[][] values) {
this.values = values;
this.size = countOfElements(values);
}
private int countOfElements(int[][] values) {
int count = 0;
for (int[] row : values) {
count += row.length;
}
return count;
}
#Override
public boolean hasNext() {
return position < size;
}
#Override
public Integer next() {
if (position >= size) {
throw new NoSuchElementException();
}
int element = values[i][j];
position++;
j++;
while (i < values.length && j >= values[i].length) {
j = 0;
i++;
}
return element;
}
}
I've also found another way:
public class IteratorFor2DArray implements Iterator {
private int[][] data;
private int i, j;
public IteratorFor2DArray(int[][] data) {
this.data = data;
}
#Override
public Integer next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
int element = data[i][j];
j++;
while (i < data.length && j >= data[i].length) {
j = 0;
i++;
}
return element;
}
#Override
public boolean hasNext() {
return (i < data.length && j < data[i].length);
}
}
I'm writing a program that creates a maze as a 2d array. I've run into a hiccup, and that is ArrayIndexOutOfBoundsException. It is pointing to maze[0][0] = "S" in the drawMaze method. I'm scratching my head at this, I have no idea why it's throwing an error.
import java.util.Random;
public class LA2_MazeSolver {
private int rows;
private int cols;
private String[][] maze = new String[rows][cols];
LA2_MazeInput mi = new LA2_MazeInput();
public void setNumRows(int numRows) {
this.rows = numRows;
}
public void setNumCols(int numCols) {
this.cols = numCols;
}
public int getNumRows() {
return this.rows;
}
public int getNumCols() {
return this.cols;
}
public void drawMaze() {
Random r = new Random();
maze[0][0] = "S";
maze[rows - 1][cols - 1] = "D";
int limit = ((rows * cols) / 3);
for (int i = r.nextInt(limit) + 1; i < limit; i++) {
maze[r.nextInt(rows) - 1][r.nextInt(cols) - 1] = "#";
}
for (int i = 0; i < maze.length; i++) {
for (int c = 0; c < maze[0].length; c++) {
if (!(maze[i][c].matches("#")) && !(maze[i][c].matches("S")) && !(maze[i][c].matches("D"))) {
maze[i][c] = Integer.toString(r.nextInt(100) + 1);
}
}
}
}
public void printMaze() {
}
/*public boolean isSolvable() {
return solveMazeRecursively(this.rows, this.cols);
}
private boolean solveMazeRecursively(int row, int col) {
}*/
public void printResult() {
}
}
It's simple. You are getting the Array Index Out of Bound exception because you are exceeding the array boundaries.
I've run into a hiccup, and that is ArrayIndexOutOfBoundsException. It is pointing to "maze[0][0] = "S";"
You have declared maze in the following block
private int rows;
private int cols;
private String[][] maze = new String[rows][cols];
Note that you are specifying a size of 'rows' and 'cols' for 'maze'. But these values are 0 and 0 respectively. See that you are not giving a value to rows and cols at the time of initialization. So the default value of int primitives declared as class members is 0.
To fix this problem, initialize rows and cols to a value greater than 0.
In Java, you can't make a definition like private String[][] maze = new String[rows][cols]; outside of the constructor. At that point in the the code, the value for row and col have not been defined and so something like private String[][] maze = new String[rows][cols]; won't have well defined behaviour (row and col may in fact be 0, who knows).
Try instead something like this:
private int row;
private int col;
private String[][] maze;
public LA2_MazeSolver(int row, int col) {
this.row = row;
this.col = col;
maze = new String[row][col]
}
Now when you create a LA2_MazerSolver object, you will dynamically create an array of the correct size to use (for example solver = new LA2_MazeSolver(row, col)).