How do I fix this ArrayIndexOutOfBoundsException in my hashtable? - java

I was wondering if anyone could help me this ArrayIndexOutOfBoundsException that occurs when trying to run a tester class.
The exception occurs at the remove method within the hashtable file. I have tried switching out my code with my friend's code but that didn't work either.
Any help would be greatly appreciated
===========================================================================
Here is the HashTable :
public class HashTable {
Object[] hTable;
int mSize;
int size;
HashTable() {
mSize = 101;
hTable = new Object[mSize];
}
HashTable(int initCap) {
mSize = initCap;
}
Object put(Object key, Object value) {
if (size == mSize) {
throw new IllegalStateException("No room within the hashtable");
}
int hashC = key.hashCode();
int index = hashC % mSize;
size++;
while (index < hTable.length) {
if (hTable[index] == null) {
hTable[index] = new Entry(key, value);
size++;
return null;
} else if (((Entry) hTable[index]).key.equals(key)) {
Object prevVal = ((Entry) hTable[index]).val;
hTable[index] = new Entry(key, value);
return prevVal;
} else if (((Entry) hTable[index]).rCheck) {
hTable[index] = new Entry(key, value);
while (index < hTable.length) {
index++;
if (hTable[index] == null) {
size++;
return null;
} else if (((Entry) hTable[index]).key.equals(key)) {
Object prevVal = ((Entry) hTable[index]).val;
((Entry) hTable[index]).remove();
return prevVal;
}
}
}
index++;
}
if (hTable[index] == null) {
hTable[index] = new Entry(key, value);
return null;
} else {
Object oldEntry = ((Entry) hTable[index]).val;
hTable[index] = new Entry(key, value);
return oldEntry;
}
}
Object get(Object key) {
int hashC = key.hashCode();
int index = hashC % mSize;
return ((Entry) hTable[index]).val;
}
Object remove(Object key) {
int hashC = key.hashCode();
int index = hashC % mSize;
Object returnObj = null;
while (hTable[index] != null) { //here is where the OutOfBounds error occurs
if (((Entry) hTable[index]).key.equals(key)) {
returnObj = ((Entry) hTable[index]).val;
((Entry) hTable[index]).remove();
size--;
break;
}
index++;
}
return returnObj;
}
int size() {
return size;
}
#Override
public String toString() {
String returnString = "";
for (int i = 0; i < hTable.length; i++) {
if (hTable[i] == null || ((Entry) hTable[i]).rCheck) {
returnString += "dummy\n";
continue;
}
returnString += "Index: " + i +
" \n Key: " + ((Integer) (((Entry) hTable[i]).key)).intValue() % 101 +
"\nValue: " + (String) (((Entry) hTable[i]).val) +
"\n++++++++++++++++++++++++++++++++++++++++++++++\n";
}
return returnString;
}
private class Entry {
Object key;
public boolean rCheck;
public Object val;
Entry() {
key = null;
val = null;
rCheck = false;
}
Entry(Object k, Object v) {
key = k;
val = v;
rCheck = false;
}
Object value() {
return val;
}
Object key() {
return key;
}
void remove() {
rCheck = true;
}
public String toString() {
return "";
}
}
}
Here is the hash table tester:
import java.io.*;
import java.util.*;
public class hashTest {
public static void main(String args[]) throws FileNotFoundException {
HashTable hashTable = new HashTable();
Scanner fileRead = new Scanner(new File("data1.txt"));
while(fileRead.hasNext()) {
Object key = fileRead.next();
fileRead.next();
Object value = fileRead.nextLine();
hashTable.put(key, value);
System.out.println(hashTable.get(key));
}
Scanner fileRead2 = new Scanner(new File("data2.txt"));
while(fileRead2.hasNext()){
Object key = fileRead2.next();
hashTable.remove(key);
fileRead2.nextLine();
}
Scanner fileRead3 = new Scanner(new File("data3.txt"));
while(fileRead3.hasNext()){
Object key = fileRead3.next();
fileRead3.next();
Object value = fileRead3.nextLine();
hashTable.put(key, value);
}
Scanner fileRead4 = new Scanner(new File("data4.txt"));
while(fileRead4.hasNext()){
Object key = fileRead4.next();
fileRead4.next();
Object value = fileRead4.nextLine();
hashTable.put(key, value);
}
}
}
===========================================================================
In the shared google drive link below you will find a zip containing data inputs.
https://drive.google.com/file/d/1iYrzWl9mtv_io3q7K1_m2EtPFUXGbC3p/view?usp=sharing

Your Problem is at this code block:
while (index < hTable.length) {
index++;
if (hTable[index] == null)...
At the last iteration index will be the same as hTable.length. In your Example index will be 100 where the condition will be accepted. In the next step index will be incremented: index = 101. At hTable[101] the ArrayIndexOutOfBoundsException will occur.

Related

B-Tree implementing toString method in Node Class that is giving this error: Cannot invoke forEach((<no type> c) -> {}) on the array type Node<E>[]]

I have Implemented B-Tree, I have given toString to Implement method in Node class as it but its giving errot in this line children.forEach(c ->builder.append(c.toString(depth + 1))); I have tried various methods but not worked
here is other B-Tree files and pdf where is given toString Methods and other Instruction check out these files
toString code
import java.util.Arrays;
import java.util.Comparator;
import java.util.LinkedList;
import java.util.List;
public class Node<E extends Comparable<E>> {
public int nodeLocation;
public int index;
private E[] keys = null;
int keysSize = 0;
public Node<E>[] children = null;
public Node<E>[] elements;
int childrenSize = 0;
private Comparator<Node<E>> comparator = new Comparator<Node<E>>() {
#Override
public int compare(Node<E> arg0, Node<E> arg1) {
return arg0.getKey(0).compareTo(arg1.getKey(0));
}
};
protected Node<E> parent = null;
Node(Node<E> parent, int maxKeySize, int maxChildrenSize) {
this.parent = parent;
this.keys = (E[]) new Comparable[maxKeySize + 1];
this.keysSize = 0;
this.children = new Node[maxChildrenSize + 1];
this.childrenSize = 0;
}
E getKey(int index) {
return keys[index];
}
int indexOf(E value) {
for (int i = 0; i < keysSize; i++) {
if (keys[i].equals(value))
return i;
}
return -1;
}
void addKey(E value) {
keys[keysSize++] = value;
Arrays.sort(keys, 0, keysSize);
}
E removeKey(E value) {
E removed = null;
boolean found = false;
if (keysSize == 0)
return null;
for (int i = 0; i < keysSize; i++) {
if (keys[i].equals(value)) {
found = true;
removed = keys[i];
} else if (found) {
// shift the rest of the keys down
keys[i - 1] = keys[i];
}
}
if (found) {
keysSize--;
keys[keysSize] = null;
}
return removed;
}
E removeKey(int index) {
if (index >= keysSize)
return null;
E value = keys[index];
for (int i = index + 1; i < keysSize; i++) {
// shift the rest of the keys down
keys[i - 1] = keys[i];
}
keysSize--;
keys[keysSize] = null;
return value;
}
int numberOfKeys() {
return keysSize;
}
Node<E> getChild(int index) {
if (index >= childrenSize)
return null;
return children[index];
}
int indexOf(Node<E> child) {
for (int i = 0; i < childrenSize; i++) {
if (children[i].equals(child))
return i;
}
return -1;
}
boolean addChild(Node<E> child) {
child.parent = this;
children[childrenSize++] = child;
Arrays.sort(children, 0, childrenSize, comparator);
return true;
}
boolean removeChild(Node<E> child) {
boolean found = false;
if (childrenSize == 0)
return found;
for (int i = 0; i < childrenSize; i++) {
if (children[i].equals(child)) {
found = true;
} else if (found) {
// shift the rest of the keys down
children[i - 1] = children[i];
}
}
if (found) {
childrenSize--;
children[childrenSize] = null;
}
return found;
}
Node<E> removeChild(int index) {
if (index >= childrenSize)
return null;
Node<E> value = children[index];
children[index] = null;
for (int i = index + 1; i < childrenSize; i++) {
// shift the rest of the keys down
children[i - 1] = children[i];
}
childrenSize--;
children[childrenSize] = null;
return value;
}
int numberOfChildren() {
return childrenSize;
}
/**
* {#inheritDoc}
*/
public String toStringg() {
return toString(0);
}
// // based on what toString() does, think about what ‘elements’ and ‘children’
// can be
private String toString(int depth) {
StringBuilder builder = new StringBuilder();
String blankPrefix = new String(new char[depth]).replace("\0", "\t");
List<String> printedElements = new LinkedList<>();
for (Node<E> e : elements)
printedElements.add(e.toString());
String eString = String.join(" :: ", printedElements);
builder.append(blankPrefix).append(eString).append("\n");
children.forEach(c -> builder.append(c.toString(depth + 1))); // this line is giving error
return builder.toString();
}
}
I Have Gievn pdf File where is gievn insructions and code implement I have tried to change childern but not worked I am bound to not make changes in gievn toString method
Arrays in Java doesn't declare their own behavior (don't try to reproduce your experience from languages like JavaScript and TypeScript, where Arrays have methods).
Therefore, you can't invoke method forEach() on the children array (this method is accessible with implementations of Iterable interface, like Collections).
You can use an enhanced for-loop instead:
for (Node<E> node : children) {
builder.append(node.toString(depth + 1));
}
Alternatively, if you declare the property children as a List you'll be able use forEach() with it:
public List<Node<E>> children;
Judging by your assignment requirements, that what you're expected to do.
That would require changing all the methods that make use of children because you can't dial with a List in the same way as with an array. I.e. you would need to use the behavior of the List interface.
children[i] would turn to children.get(i). And children[i] = ... would become children.set(i, ...), or children.add(...).

Parametrized object cannot be resolved to variable [duplicate]

This question already has answers here:
scope error in if statement in java program
(3 answers)
Closed 7 years ago.
I have this piece of code:
#SuppressWarnings("unchecked")
public void put(K key,V value){
if(this.containsKey(key)){
TableEntry<K,V> foundKey = (TableEntry<K,V>)this.getTableEntry(key);
foundKey.setValue(value);
} else{
int slotNumber = Math.abs(key.hashCode()) % size;
TableEntry<K,V> candidate = (TableEntry<K,V>) elements [slotNumber];
}
// empty slot
if(candidate == null){
elements[slotNumber] = new TableEntry(key,value,null);
}else{
while(candidate != null){
candidate = candidate.next;
}
candidate.next = new TableEntry(key,value,null);
}
}
Variables candidate and slotNumber are underlined in Eclipse, as are the invocations of the TableEntry() constructor. Can you tell me why I can't compare for example candidate with null?
If you need, here is complete class (Hash table):
package hr.fer.oop.lab3.prob2;
public class SimpleHashtable<K,V> {
private V[] elements;
private static int defaultsize = 16;
private int size;
public SimpleHashtable(){
this(defaultsize);
}
#SuppressWarnings("unchecked")
public SimpleHashtable(int initialCapacity){
if(initialCapacity < 1) {
throw new IllegalArgumentException("Capacity must be at least 1.");
}
elements = (V[])new Object[calculateCapacity(initialCapacity)];
}
public int calculateCapacity(int number){
int result = 2;
while(result < number){
result = result << 1;
}
System.out.println(result);
return result;
}
#SuppressWarnings("unchecked")
public void put(K key,V value){
if(this.containsKey(key)){
TableEntry<K,V> foundKey = (TableEntry<K,V>)this.getTableEntry(key);
foundKey.setValue(value);
} else{
int slotNumber = Math.abs(key.hashCode()) % size;
TableEntry<K,V> candidate = (TableEntry<K,V>) elements [slotNumber];
}
// empty slot
if(candidate == null){
elements[slotNumber] = new TableEntry(key,value,null);
}else{
while(candidate != null){
candidate = candidate.next;
}
candidate.next = new TableEntry(key,value,null);
}
}
#SuppressWarnings("unchecked")
private TableEntry<K,V> getTableEntry(K key) {
int slotNumber = Math.abs(key.hashCode()) % this.size;
TableEntry<K,V> candidate = (TableEntry<K,V>) elements [slotNumber];
while(candidate != null){
if(key.equals(candidate.getKey())){
return candidate;
}
candidate = candidate.next;
}
return null;
}
private boolean containsKey(K key) {
return false;
}
private static class TableEntry<K,V>{
K key;
V value;
TableEntry next = null;
public TableEntry(K key, V value, TableEntry next){
this.key = key;
this.value = value;
this.next = next;
}
K getKey(){
return key;
}
V getValue(){
return value;
}
void setValue(V value){
this.value = value;
}
#Override
public String toString(){
return "Key:" + (String)key + "Value:" + (String)value;
}
}
}
Your declarations of the candidate and slotNumber variables are visible only within the innermost block containing them, which in this case contains nothing else. It looks like you want to move the code that uses those variables into that block (as opposed to moving the declarations out of it):
#SuppressWarnings("unchecked")
public void put(K key, V value){
if (this.containsKey(key)) {
TableEntry<K, V> foundKey = this.getTableEntry(key);
foundKey.setValue(value);
} else {
int slotNumber = Math.abs(key.hashCode()) % size;
TableEntry<K,V> candidate = (TableEntry<K, V>) elements[slotNumber];
// empty slot
if (candidate == null) {
elements[slotNumber] = new TableEntry<K, V>(key, value, null);
} else {
while (candidate != null) {
candidate = candidate.next;
}
candidate.next = new TableEntry<K, V>(key, value, null);
}
}
}
You can't compare then - nor access them at all - at those locations because they're out of scope. You have declared them within the 'else' part of your if-statement, so that's their scope.
So, solutions are to either move the declaration outside the if, or move your code to inside that 'else' code block. Which you choose depends on whether you want to access 'slotNumber' or 'candidate' subsequently; if not, then personally I'd prefer the second, so :
if(this.containsKey(key)){
TableEntry<K,V> foundKey = (TableEntry<K,V>)this.getTableEntry(key);
foundKey.setValue(value);
} else{
int slotNumber = Math.abs(key.hashCode()) % size;
TableEntry<K,V> candidate = (TableEntry<K,V>) elements [slotNumber];
// empty slot
if(candidate == null){
elements[slotNumber] = new TableEntry(key,value,null);
}else{
while(candidate != null){
candidate = candidate.next;
}
candidate.next = new TableEntry(key,value,null);
}
}

Remove at index function removes all elements before index

I use this remove method to remove the 3rd element of list. But it removes all the elements before the specified index. So if Jhon, Sam, Philip, Emma are the list elements, if I remove 3rd element, the only remaining element is Nick. How can I fix this?
import java.util.*;
class List {
Customer listPtr;
int index;
public void add(Customer customer) {
Customer temp = customer;
if (listPtr == null) {
listPtr = temp;
index++;
} else {
Customer x = listPtr;
while (x.next != null) {
x = x.next;
}
x.next = temp;
index++;
}
}
public void remove(int index) {
int size = size();
Customer tmp = listPtr, tmp2;
int i = 0;
while (i != size) {
if ((i + 1) == index) {
tmp2 = tmp;
listPtr = tmp2.next;
break;
}
tmp = tmp.next;
++i;
}
}
public int size() {
int size = 0;
Customer temp = listPtr;
while (temp != null) {
temp = temp.next;
size++;
}
return size;
}
public void printList() {
Customer temp = listPtr;
while (temp != null) {
System.out.println(temp);
temp = temp.next;
}
}
}
class DemoList {
public static void main(String args[]) {
List list = new List();
Customer c1 = new Customer("10011", "Jhon");
Customer c2 = new Customer("10012", "Sam");
Customer c3 = new Customer("10013", "Philip");
Customer c4 = new Customer("10014", "Emma");
list.add(c1);
list.add(c2);
list.add(c3);
list.add(c4);
list.remove(3);
System.out.println(list.size());
list.printList();
}
}
class Customer {
String id;
String name;
Customer next;
public Customer(String id, String name) {
this.id = id;
this.name = name;
}
public String toString() {
return id + " : " + name;
}
public boolean equals(Object ob) {
Customer c = (Customer) ob;
return this.id.equals(c.id);
}
}
There are several problems with the remove() method.
First of all, you should only be changing listPtr if index == 0.
In all other cases, you need to adjust node.next of the node at position index - 1.
P.S. Having index as a data member of List looks like an accident waiting to happen.
public void remove(int index) {
if (i == 0) {
// TODO: do some checks (listPtr is set, has next...)
listPtr = listPtr.next;
}
else {
int currentIndex = 0;
Customer currentElement = listPtr;
while (currentIndex != size()) {
if ((currentIndex + 1) == index) {
currentElement.next = currentElement.next.next;
break;
}
currentElement = currentElement.next;
currentIndex++;
}
}
}

Java calculator version 4

The calculator is now almost working. It now gives me the same answer for every equation it reads in?
the output ends up as:
49+62*61-36
15.666666666666668
4/64
15.666666666666668
(53+26)
15.666666666666668
0*72
15.666666666666668
21-85+75-85
15.666666666666668
90*76-50+67
15.666666666666668
46*89-15
15.666666666666668
34/83-38
15.666666666666668
20/76/14+92-15
15.666666666666668
5*10/3-1
15.666666666666668
Instead of having the answer for each equation there?
Have i missed something out in my methods?
Thanks
All code is shown below. Any help will be much appreciated.
Stack class:
import java.util.Iterator;
import java.util.NoSuchElementException;
public class myStack<Item> implements Iterable<Item> {
private int N; // size of the stack
private Node first; // top of stack
private class Node {
private Item item;
private Node next;
}
/**
* Create an empty stack.
*/
public myStack() {
first = null;
N = 0;
assert check();
}
public boolean isEmpty() {
return first == null;
}
public int size() {
return N;
}
public void push(Item item) {
Node oldfirst = first;
first = new Node();
first.item = item;
first.next = oldfirst;
N++;
assert check();
}
public Item pop() {
if (isEmpty())
throw new NoSuchElementException("Stack underflow");
Item item = first.item; // save item to return
first = first.next; // delete first node
N--;
assert check();
return item; // return the saved item
}
public Item peek() {
if (isEmpty())
throw new NoSuchElementException("Stack underflow");
return first.item;
}
public String toString() {
StringBuilder s = new StringBuilder();
for (Item item : this)
s.append(item + " ");
return s.toString();
}
// check internal invariants
private boolean check() {
if (N == 0) {
if (first != null)
return false;
} else if (N == 1) {
if (first == null)
return false;
if (first.next != null)
return false;
} else {
if (first.next == null)
return false;
}
// check internal consistency of instance variable N
int numberOfNodes = 0;
for (Node x = first; x != null; x = x.next) {
numberOfNodes++;
}
if (numberOfNodes != N)
return false;
return true;
}
public Object[] toArray(String[] elementData) {
return (Object[]) elementData.clone();
}
public Iterator<Item> iterator() {
return new ListIterator();
}
// did not implement remove as it was not needed
private class ListIterator implements Iterator<Item> {
private Node current = first;
public boolean hasNext() {
return current != null;
}
public void remove() {
throw new UnsupportedOperationException();
}
public Item next() {
if (!hasNext())
throw new NoSuchElementException();
Item item = current.item;
current = current.next;
return item;
}
}
}
Array list class
import java.util.Arrays;
public class myArrayList<Item>{
private Object[] myStore;
private int actSize = 0;
public myArrayList() {
myStore = new Object[100];
}
public Object get(int index) {
if (index < actSize) {
return myStore[index];
} else {
throw new ArrayIndexOutOfBoundsException();
}
}
public void add(Object obj) {
if (myStore.length - actSize <= 0) {
increaseListSize();
}
myStore[actSize++] = obj;
}
public Object remove(int index) {
if (index < actSize) {
Object obj = myStore[index];
myStore[index] = null;
int tmp = index;
while (tmp < actSize) {
myStore[tmp] = myStore[tmp + 1];
myStore[tmp + 1] = null;
tmp++;
}
actSize--;
return obj;
} else {
throw new ArrayIndexOutOfBoundsException();
}
}
public int size() {
return actSize;
}
private void increaseListSize() {
myStore = Arrays.copyOf(myStore, myStore.length * 2);
}
#SuppressWarnings("unchecked")
public <T> T[] toArray(T[] a) {
if (a.length < size())
// Make a new array of a's runtime type, but my contents:
return (T[]) Arrays.copyOf(myStore, size(), a.getClass());
System.arraycopy(myStore, 0, a, 0, size());
if (a.length > size())
a[size()] = null;
return a;
}
}
The TestClass for equation handling
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.StringTokenizer;
public class TestClass {
private static final int LEFT_ASSOC = 0;
private static final int RIGHT_ASSOC = 1;
static String OPERATORS1 = "+-*/()";
// Operators
private static final Map<String, int[]> OPERATORS = new HashMap<String, int[]>();
static {
// Map<"token", []{precedence, associativity}>
OPERATORS.put("+", new int[] { 0, LEFT_ASSOC });
OPERATORS.put("-", new int[] { 0, LEFT_ASSOC });
OPERATORS.put("*", new int[] { 5, LEFT_ASSOC });
OPERATORS.put("/", new int[] { 5, LEFT_ASSOC });
OPERATORS.put("(", new int[] {1, LEFT_ASSOC});
OPERATORS.put(")", new int[] {1, LEFT_ASSOC});
}
private static boolean isOperator(String token) {
return OPERATORS.containsKey(token);
}
// Test associativity of operator token
private static boolean isAssociative(String token, int type) {
if (!isOperator(token)) {
throw new IllegalArgumentException("Invalid token: " + token);
}
if (OPERATORS.get(token)[1] == type) {
return true;
}
return false;
}
// Compare precedence of operators.
private static final int cmpPrecedence(String token1, String token2) {
if (!isOperator(token1) || !isOperator(token2)) {
throw new IllegalArgumentException("Invalid tokens: " + token1
+ " " + token2);
}
return OPERATORS.get(token1)[0] - OPERATORS.get(token2)[0];
}
public static String[] infixToRPN(String[] inputTokens) {
myArrayList<String> out = new myArrayList<String>();
myStack<String> stack = new myStack<String>();
// For each token
for (String token : inputTokens) {
StringTokenizer tokens = new StringTokenizer(token,OPERATORS1,true);
while (tokens.hasMoreTokens()) {
token = tokens.nextToken();
// If token is an operator
if (isOperator(token)) {
// While stack not empty AND stack top element
// is an operator
while (!stack.isEmpty() && isOperator(stack.peek())) {
if ((isAssociative(token, LEFT_ASSOC) && cmpPrecedence(
token, stack.peek()) <= 0)
|| (isAssociative(token, RIGHT_ASSOC) && cmpPrecedence(
token, stack.peek()) < 0)) {
out.add(stack.pop());
continue;
}
break;
}
// Push the new operator on the stack
stack.push(token);
}
// If token is a left bracket '('
else if (token.equals("(")) {
stack.push(token);
}
// If token is a right bracket ')'
else if (token.equals(")")) {
while (!stack.isEmpty() && !stack.peek().equals("(")) {
out.add(stack.pop());
}
stack.pop();
}
// If token is a number
else {
out.add(token);
}
}
while (!stack.isEmpty()) {
out.add(stack.pop());
}
}
String[] output = new String[out.size()];
return out.toArray(output);
}
public static double RPNtoDouble(String[] tokens) {
myStack<String> stack = new myStack<String>();
// For each token
for (String token : tokens) {
//System.out.println( "Working this token: " + token );
// If the token is a value push it onto the stack
if (!isOperator(token)) {
stack.push(token);
} else {
// Token is an operator: pop top two entries
Double d2 = Double.valueOf(stack.pop());
Double d1 = Double.valueOf(stack.pop());
// Get the result
Double result = token.compareTo("+") == 0 ? d1 + d2 : token
.compareTo("-") == 0 ? d1 - d2
: token.compareTo("*") == 0 ? d1 * d2 : d1 / d2;
// Push result onto stack
stack.push(String.valueOf(result));
}
}
return Double.valueOf(stack.pop());
}
static public void main(String[] args) throws IOException {
File file = new File("testEquations.txt");
String[] lines = new String[1];
try {
FileReader reader = new FileReader(file);
#SuppressWarnings("resource")
BufferedReader buffReader = new BufferedReader(reader);
int x = 0;
String s;
while ((s = buffReader.readLine()) != null) {
lines[x] = s;
x++;
}
} catch (IOException e) {
System.exit(0);
}
// test printing string array
for (String s : lines) {
System.out.println("" + s);
String[] output =infixToRPN(lines);
System.out.println(RPNtoDouble(output));
}
}
}
Your problem is here:
String[] lines = new String[1];
try {
FileReader reader = new FileReader(file);
#SuppressWarnings("resource")
BufferedReader buffReader = new BufferedReader(reader);
int x = 0;
String s;
while ((s = buffReader.readLine()) != null) {
lines[x] = s;
x++;
}
...
you define array of string with a size = 1 but you don't check inside the loop if x is getting out of the borders of this array.
Do somethink like this:
int Size = // define the size..;
String[] lines = new String[Size];
...
while (x < Size && (s = buffReader.readLine()) != null)) {
lines[x] = s;
x++;
}
when your x becames bigger then Size, x < Size will evaluate false, thus getting out of the loop.
About one of the error you are getting ArrayIndexOutOfBoundsException:
Thrown to indicate that an array has been accessed with an illegal
index. The index is either negative or greater than or equal to the
size of the array. (source)
The other error NoSuchElementException :
Thrown by the nextElement method of an Enumeration to indicate that
there are no more elements in the enumeration (source).
Another problem is here:
// test printing string array
for (String s : lines)
{
System.out.println("" + s);
String[] output =infixToRPN(lines);
System.out.println(RPNtoDouble(output));
}
You have to pass s, and not lines into method infixToRPN, thats why you are getting the same output, because you are giving the same input.
Remember that infixToRPN receives a String [] not a string like 's', but this I leave to you to find a workaround.

Simple HashTable implementation using an array in Java?

I'm having a problem with implementing a very simple HashTable using an array. The problem is that the first Item put in the HashTable is always AVAILABLE. Maybe you guys can see what is going wrong. This is the HashTable class:
public class HashTable {
private Item[] data;
private int capacity;
private int size;
private static final Item AVAILABLE = new Item("Available", null);
public HashTable(int capacity) {
this.capacity = capacity;
data = new Item[capacity];
for(int i = 0; i < data.length; i++) {
data[i] = AVAILABLE;
}
size = 0;
}
public int size() {
return size;
}
public int hashThis(String key) {
return key.hashCode() % capacity;
}
public Object get(String key) {
int hash = hashThis(key);
while(data[hash] != AVAILABLE && data[hash].key() != key) {
hash = (hash + 1) % capacity;
}
return data[hash].element();
}
public void put(String key, Object element) {
if(key != null) {
size++;
int hash = hashThis(key);
while(data[hash] != AVAILABLE && data[hash].key() != key) {
hash = (hash + 1) % capacity;
}
data[hash] = new Item(key, element);
}
}
public Object remove(String key) {
// not important now.
throw new UnsupportedOperationException("Can't remove");
}
public String toString() {
String s = "<HashTable[";
for(int i = 0; i < this.size(); i++) {
s += data[i].toString();
if(i < this.size() - 1) {
s += ",";
}
}
s += "]>";
return s;
}
}
For more clarity, this is the Item class:
public class Item {
private String key;
private Object element;
public Item(String key, Object element) {
this.setKey(key);
this.setElement(element);
}
public String key() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public Object element() {
return element;
}
public void setElement(Object element) {
this.element = element;
}
public String toString() {
String s = "<Item(";
s += this.key() + "," + this.element() + ")>";
return s;
}
}
To give an example:
HashTable ht = new HashTable(10);
ht.put("1", "a");
The output of toString() after putting has to be:
"<HashTable[<Item(1,a)>]>"
but I get:
"<HashTable[<Item(Available,null)>]>"
update: I should probably mention that the next Item gets put correctly and the one after that is not again.
I think the problem is in your toString method. You loop for 0 - size when size = 1 so once so you only print out the first value in your hashTable problem is the first value in your hash table is not a real value it's an AVAILABLE you have to do something like this
EDIT: Sorry I forgot to move the index over.
public String toString() {
String s = "<HashTable[";
int i = 0;
int count = 0;
while(count < this.size()) {
//Skip the AVAILABLE cells
if(data[i] == AVAILABLE) {
i++;
continue;
}
s += data[i].toString();
if(count < this.size() - 1) {
s += ",";
}
count++;
}
s += "]>";
return s;
}
Try this for toString() if still interested in the solution, I ran it and its fine:
public String toString()
{
String s = "<HashTable[";
for (int i = 0; i < this.capacity; i++)
{
if (data[i].Element != null)
{
s += data[i].toString();
if (i < this.size - 1)
{
s += ",";
}
}
}
s += "]>";
return s;
}

Categories

Resources