This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 2 years ago.
I tried to build the node object with a arraylist element for adding child node, and initialized successfully. However when i tried to add nodes into the arraylist the exception happened. How to solve the problem?
public class nodes{
int value=-2;
boolean root=false;
nodes parent;
ArrayList<nodes>Children;
public nodes(int value,ArrayList Children) {
this.value=value;
this.Children=Children;
}
public void setParent(nodes parent) {
this.parent=parent;
}
public void Add(nodes child) {
this.Children.add(child);
}
}
public class TreeHeight {
int n;
int parent[];
nodes Nodes[];
void read() throws IOException {
FastScanner in = new FastScanner();
n = in.nextInt();
ArrayList[]Children=new ArrayList[n];
parent = new int[n];//parent is an array that contains all elements
Nodes=new nodes [n];
for (int i = 0; i < n; i++) {
//parent[i]= ;
//index[i]=i;
Nodes[i]=new nodes(in.nextInt(),Children[i]);
}
//Nodes[0].Add(Nodes[1]);
for (int vertex = 0; vertex < n; vertex++) {
if(Nodes[vertex].value==-1) {Nodes[vertex].root=true;
}
for(int j=0;j<n;j++) {
if(Nodes[j].value==vertex) {
Nodes[j].setParent(Nodes[vertex]);
Nodes[vertex].Add(Nodes[j]);
}
}
}
}
I don't see add values for this array?
ArrayList[]Children=new ArrayList[n];
but have get value in this line?
Nodes[i]=new nodes(in.nextInt(),Children[i]);
Related
This question already has answers here:
Method for adding Objects into a fixed collection(Array) in Java
(3 answers)
Closed 10 months ago.
In my program I have two private variable
private Object[] array;
private int place;
I have initialized these variables in the constructor
public Arrays() {
array = new Object[10];
place = 0;
}
I am trying to properly implement the following method, this is what I have so far
public boolean add(Object new) {
for(int j = place+1; j <= 0; j++){
array[j] = new;
}
place++;
return true;
}
I am having trouble with placing the object 'new' into the next unoccupied cell
Just assign to the next free slot. new is a reserved keyword.
public boolean add(Object newItem) {
vals[place++]=newItem;
return true;
}
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 2 years ago.
I have written a condition in code where if the value of Object is null, it should initialize a new object, but I am getting null pointer exception at the comparison statement itself. as per my knowlwdge we van compare two null values.
Not sure what a I missing. Below is my code
public class TrieNode
{
static final int Alphabet_Size = 26;
class Tried
{
Tried children[] = new Tried[Alphabet_Size];
boolean isEndofWord;
Tried()
{
isEndofWord = false;
/*for(int i=0; i<Alphabet_Size; i++)
children[i] = null; */
}
};
static Tried root;
public void insert(String key)
{
Tried note = root;
int index;
int itr;
for(itr=0; itr<key.length(); itr++)
{
index = key.charAt(itr)-'a';
if(note.children[index]==null) // Getting Null pointer Exception here
{
note.children[index] = new Tried();
}
note = note.children[index];
}
note.isEndofWord = true;
}
public boolean search(String key)
{
Tried note = root;
int index;
int itr;
for(itr=0; itr<key.length(); itr++)
{
index = key.charAt(itr)-'a';
if(note.children[index]==null)
return false;
note = note.children[index];
}
return (note!=null && note.isEndofWord);
}
public static void main(String[] args)
{
TrieNode tr = new TrieNode();
String keys[] = {"the", "their", "Aakash", "Aayush"};
for(int i=0; i<keys.length; i++)
{
tr.insert(keys[i]);
}
}
}
I Have tried adding null values for all the indexes in array(see the commented part of code) but even that is not helping
if note itself is null you cannot perform note.children[index] try something like if(note==null) then initialize object
This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 6 years ago.
I'm writing a hash table code. Taking mode according to table size.I want to start with table -1 and null.I understand that it is empty. Java hash table ready.So I do not find many examples.
My fill_in method is not running.
class Node{
int index;
int number;
Node next;
public Node(int index,int number,Node next){
this.index=index;
this.next=next;
this.number=number;
}
}
class Table{
int max_row;
public Table(int size){
this.max_row=size;
}
Node rows[]= new Node[max_row];
public void fill_in(){
for(int i=0; i<max_row;i++)
rows[i]=new Node(-1,-1,null);
}
You should initialize your array in constructor, because now it is initialized with unknown max_row.
class Table {
int max_row;
Node rows[];
public Table(int size) {
this.max_row = size;
rows = new Node[max_row];
}
You are trying to set the size of your Node array to the size of the value in max_size before it has been initialized. Change your class to this
class Table{
int max_row;
Node rows[];
public Table(int size){
max_row = size;
rows = new Node[max_row];
}
public void fill_in(){
for(int i=0; i<max_row;i++)
rows[i]=new Node(-1,-1,null);
}
}
This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 6 years ago.
I need to create an array list using generics. My add method seems to work sometimes, however my get method appears to have a good amount of problems and i don't receive a compile error. However when i try to get an object from the Array list using my get method it throws a java out of bounds exception. here i what i have so far, and i am using BlueJ. Also, the instructions were to set the initial "illusion" length to zero.
public class AL <X> {
private X[]data;
private int count;
public AL() {
count = 0;
data = (X[]) new Object[0];
}
public void add (X v) {
if (data.length != count) {
data[count] = v;
count++;
} else {
X [] newdata = (X[]) new Object[data.length * 2];
for (int i = 0; i < data.length; i++) {
newdata[i] = data [i];
}
count++;
data = newdata;
}
}
public X get(int index) {
if (index >= count || index < 0) {
throw new ICantEven();
} else {
return data[index];
}
}
}
Your add method doesn't work, since the initial backing array you are using has a 0 length, which remains 0 even when you try to double it (since 0*2==0).
You also forgot to actually add the new element when you resize the backing array. If you hadn't forgot that, you'd get the exception in add.
First of all, change the initial size of the array created by your constructor to be positive :
data = (X[]) new Object[10];
Then add
data[count] = v;
to the else clause of your add method (just before count++;).
Your add method can be further simplified :
public AL()
{
count = 0;
data = (X[]) new Object[10];
}
public void add (X v)
{
// resize backing array if necessary
if (data.length == count)
{
X [] newdata = (X[]) new Object[data.length * 2];
for (int i = 0; i < data.length;i++ )
{
newdata[i] = data [i];
}
data = newdata;
}
// add new element
data[count] = v;
count++;
}
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I'm Java beginner, I have taken piece of code from online and trying the program on permutation. Im getting error as
Exception in thread "main"java.lang.ArrayIndexOutOfBoundsException: -1.
Can anybody help to resolve this problem. Thank you.
// Permute.java -- A class generating all permutations
import java.lang.reflect.Array;
import java.util.Iterator;
import java.util.NoSuchElementException;
public class Permute implements Iterator {
private final int size;
private final Object [] elements; // copy of original 0 .. size-1
private final Object ar; // array for output, 0 .. size-1
private final int [] permutation; // perm of nums 1..size, perm[0]=0
private boolean next = true;
// int[], double[] array won't work :-(
public Permute (Object [] e) {
size = e.length;
elements = new Object [size]; // not suitable for primitives
System.arraycopy (e, 0, elements, 0, size);
ar = Array.newInstance (e.getClass().getComponentType(), size);
System.arraycopy (e, 0, ar, 0, size);
permutation = new int [size+1];
for (int i=0; i<size+1; i++) {
permutation [i]=i;
}
}
private void formNextPermutation () {
for (int i=0; i<size; i++) {
// i+1 because perm[0] always = 0
// perm[]-1 because the numbers 1..size are being permuted
Array.set (ar, i, elements[permutation[i+1]-1]);
}
}
public boolean hasNext() {
return next;
}
public void remove() throws UnsupportedOperationException {
throw new UnsupportedOperationException();
}
private void swap (final int i, final int j) {
final int x = permutation[i];
permutation[i] = permutation [j];
permutation[j] = x;
}
// does not throw NoSuchElement; it wraps around!
public Object next() throws NoSuchElementException {
formNextPermutation (); // copy original elements
int i = size-1;
while (permutation[i]>permutation[i+1])
i--;
if (i==0) {
next = false;
for (int j=0; j<size+1; j++) {
permutation [j]=j;
}
return ar;
}
int j = size;
while (permutation[i]>permutation[j]) j--;
swap (i,j);
int r = size;
int s = i+1;
while (r>s) { swap(r,s); r--; s++; }
return ar;
}
public String toString () {
final int n = Array.getLength(ar);
final StringBuffer sb = new StringBuffer ("[");
for (int j=0; j<n; j++) {
sb.append (Array.get(ar,j).toString());
if (j<n-1) sb.append (",");
}
sb.append("]");
return new String (sb);
}
public static void main (String [] args) {
for (Iterator i = new Permute(args); i.hasNext(); ) {
final String [] a = (String []) i.next();
System.out.println (i);
}
}
}
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.
As you have not posted any stack trace. Problem is unclear. But these links may help you.
oracle docs
stackoverflow