This question already has answers here:
Do object arrays in Java have default values?
(6 answers)
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 4 years ago.
I need to assign a value to my 2 Dimension array.
I tried to code as below, but I get NullPointer Exception Error.
MethodClass[][] methodSet = new MethodClass[1][1];
methodSet[0][0].setmethodName(1);
methodSet[0][1].setmethodStatus(1);
The MethodClass file:
public class MethodClass {
private int methodName;
private int methodStatus;
public MethodClass() {
methodName = 0;
methodStatus = 0;
}
public int getmethodName() {
return methodName;
}
public int getmethodStatus() {
return methodStatus;
}
public void setmethodName(int i) {
this.methodName = i;
}
public void setmethodStatus(int status) {
this.methodStatus = status;
}
}
May I know how to initialize the value to 2 dimension array?
The NullPointerException occurs when you try to access a member of a class but the instance of that class is itself containing null value.
To prevent NullPointerException in your case, you must initialize the array values, as for Object type array the default value in positions would be NULL.
Better to do:
MethodClass[][] methodArray = new MethodClass[1][1]; //You can put any dimentions to this array, below for loop will initialize all the positions.
for (int i = 0; i < methodArray.length; i++){
for (int j = 0; j < methodArray[i].length; j++) {
methodArray[i][j] = new MethodClass();
}
}
Then you can access your methods as below:
methodArray[0][0].setmethodName(1);
methodArray[0][0].setmethodStatus(1);
You've initialized the 2D array as 1x1 which means there will only be one element in the array. Trying to use index 1 will throw an error [indexing starts from 0].
If you want to go there, initialize it as a 2x2 array.
You're basically going out of bounds, so if it were an array, you'd get an ArrayIndexOutOfBoundsException.
Initialize it like :
MethodClass[][] methodset = new MethodClass[2][2];
MethodClass[][] methodSet = new MethodClass[1][1] is only initializing your array. To initialize your elements in array you need to do the below code.
MethodClass[][] methodSet = new MethodClass[1][1];
methodSet[0][0]=new MethodClass();
methodSet[0][0].setmethodName(1);
Secondly, for methodset[0][1] you need to change the size or else it will throw ArrayIndexOutOfBoundsException.
MethodClass[][] methodSet = new MethodClass[1][2];
You are declaring a matrix of 1*1, which is of size one. There is only index as (0,0). (0,1) is invalid.
Try using the below code,
MethodClass.java
public class MethodClass {
private int methodName;
private int methodStatus;
public MethodClass() {
methodName = 0;
methodStatus = 0;
}
public MethodClass(int methodName, int methodStatus) {
this.methodName = methodName;
this.methodStatus = methodStatus;
}
public int getMethodName() {
return methodName;
}
public void setMethodName(int methodName) {
this.methodName = methodName;
}
public int getMethodStatus() {
return methodStatus;
}
public void setMethodStatus(int methodStatus) {
this.methodStatus = methodStatus;
}
}
Test.Java
public class Test {
public static void main(String a[]){
MethodClass[][] methodSet = new MethodClass[2][2];
methodSet[0][0] = new MethodClass(0, 0);
methodSet[0][1] = new MethodClass(0, 1);
methodSet[1][0] = new MethodClass(1, 0);
methodSet[1][1] = new MethodClass(1, 1);
System.out.println(methodSet);
}
}
Null pointer exception shows when you try to access a method/function of a class but the instance of that class is itself containing null value.
for example null.setmethodName(1) will throw exception.
The work around in your case is,
First initialize your MethodClass 2D array with the constructor of the class so that, each cell of the 2D array contains MethodClass instance.
MethodClass[][] methodSet = new MethodClass[1][1];
//since the array size of each cell is fixed to 1 in
//your case. So you can loop for row and column from 0 to less then 1 for 0
//indexed cells. otherwise you could also use i<methodSet.length for row and
//j<methodSet[i].length for column
for(int i=0;i<1;i++){
for(int j=0;j<1;j++){
methodSet[i][j]=new MethodClass(); // your MethodClass constructor
}
}
Then you can access your method/function as below:
methodSet[0][0].setmethodName(1); // since the size of each cell of the 2D array is one in your case and index starts from zero so only cell [0][0] is valid in this case
methodSet[0][0].setmethodStatus(1);
Related
I'm trying to return a 2-dimensional array from a function inside of a class. I don't want to create a new array inside the function because I want to return the same one I've passed into the function.
I've tried creating a new array with the same name, but it says it's already defined within the scope. I've also tried just doing (return plane;) which doesnt work because of incompatible data types. I've also tried (return plane[][];) but that doesnt work either.
public class Airplane {
private String maxSeats; //used for constructor
private char[][] plane = new char[13][6]; //array to be passed in
public char create(char[][] plane) {
plane[13][6]; //this is where I'm unsure what to do
//initialize them as '*' to start
for (int i = 0; i <= 12; i++) {
for ( int k = 0; k <= 5; k++) {
plane[i][k] = '*';
}
return plane;
}
}
I'm trying to return the array to be used in another function where I will modify it.
You have to change the return type to char[][] since you want to return a 2-dimensional array of characters and not just a single character
public class Airplane {
private String maxSeats;
private char[][] plane = new char[13][6];
public char[][] create(char[][] plane) {
// plane[13][6]; you should remove this line, it's the wrong syntax
//and it's unneeded since you've already declared this array
// this is a more compact version of your nested loop
for (int i = 0; i < 13; i++) {
Arrays.fill(plane[i], '*'); //fills the whole array with the same value
}
return plane;
}
}
I wrote this code. My aim is to write the string in char.
But i'm getting ArrayIndexOfBoundsException error.
public class Charwork {
char[] letter;
int keepInt;
public Charwork()
{
letter = new char[keepInt];
}
public void copy(String nameToCoppy)
{
this.keepInt = nameToCoppy.length();
System.out.println(this.keepInt);
for(int x = 0; x < this.keepInt;x++)
{
letter[x] = nameToCoppy.charAt(x);
System.out.println(letter[x]);
}
}
}
Your issue is your array is instantiated with a int that is null or 0. Moving that one line in your constructor to the copy function after getting string length should do the trick.
public Charwork()
{
}
public void copy(String nameToCoppy)
{
this.keepInt = nameToCoppy.length();
letter = new char[keepInt];
System.out.println(this.keepInt);
for(int x = 0; x < this.keepInt;x++)
{
letter[x] = nameToCoppy.charAt(x);
System.out.println(letter[x]);
}
}
You create an object Charworkwhile instantiating variable char[] letter with length keepInt - but keepInt is zero at the moment, beacuse int is primitive and instantinated with default 0 value.
Then, in copy method you change value of keepInt, but that's irrelevant, because an array char[] letter is already set with length 0.
I'm a beginner and I have a problem with JUnit test in the constructor of a class.
The class that I want to test is called IntSortedArray and is as follows:
public class IntSortedArray {
private int[] elements;
private int size;
public IntSortedArray() {
this.elements = new int[16];
this.size = 0;
}
public IntSortedArray(int initialCapacity) throws IllegalArgumentException {
if(initialCapacity < 0) {
throw new IllegalArgumentException("Error - You can't create an array of negative length.");
}
else {
elements = new int[initialCapacity];
size = 0;
}
}
public IntSortedArray(int[] a) {
elements = new int[a.length + 16];
for(int i = 0; i < a.length; i++)
elements[i] = a[i];
size = a.length;
insertionSort(elements);
}
//other code...
}
With Eclipse I created a class for JUnit:
public class IntSortedArrayUnitTest {
private IntSortedArray isa;
#Test
public void testConstructorArray16Elements() {
isa = new IntSortedArray();
int expected = 0;
for(int i: isa.elements) **<-- ERROR**
expected += 1;
assertEquals(expected, 16);
}
}
I started to write a test class with the intention to test all the methods of the class IntSortedArray, including constructors.
The first method testConstructorArray16Elements() wants to test the first builder.
So I thought I would check if the creation of the array elements is done properly, so the for loop counts how long elements and make sure it along 16 (as required).
But Eclipse generates (rightly) a mistake because elements is private.
How can I fix this error? I don't want to put the public field and if possible I would like to avoid creating a method public int[] getElements().
What do you recommend?
Another question: I can do two assert the same method? One to test the length of the array and the other to test that size is 0.
I hope not to have made big mistakes, this is the first time I use JUnit.
PS: how can I test the second constructor?
Thank you very much!
It looks like your class fields are declare as private but you trying to access then from outside the class. You need to provide the accessors methods in you class to make them visible:
private int[] elements;
private int size;
public static final int MAX = 16;
public int[] getElements() { ... }
public int getSize() { return size; }
Then you will be able to write below code:
isa = new IntSortedArray();
int expected = 0;
for(int i: isa.getElements()) {
expected += 1;
}
assertEquals(expected, IntSortedArray.MAX );
It looks like your constructor has created an array for 16 integers, but does not initialize it with any value. To do that you should have below code:
public IntSortedArray() {
this.elements = new int[MAX];
this.size = 0;
for (int i=0 ; i < MAX ;i++) {
elements[i] = i;
size++;
}
}
You'll have to write a getter method for your array, or implement an Iterator
Hello I have implemented this basic program which should sort out the strings that are inserted however it somehow is failing to insert the strings .
For example if I implement :
TestSort t = new TestSort();
t.i("abc");
t.i("aab");
Can anybody see the error and help me fix this error please ?
Thank you
Here is the code :
public class TestSort {
private int length;
String[] data;
public TestSort() {
length = 0;
}
public void i(String value) {
data[length] = value;
setSorted(data);
length++;
}
public void setSorted(String data[]) {
for(int i = data.length-1; i >= 0; i--) {
for(int j = 0; j < i; j++) {
if(data[j].compareTo(data[j + 1]) > -1) {
String temp = data[j];
data[j] = data[j + 1];
data[j + 1] = temp;
}
}
}
for(int i = 0; i < data.length; i++) {
System.out.print(data[i] +" ");
}
}
}
You don't initialize the array data. So it is set null, and accesses with data[i] will get you an NullPointerException. Even if you initialize this field, it will not work, as Arrays in Java have a fixed size, you have to reallocate the Array, if you insert a new value. You should try a List-implementation instead.
So the code should initialize in the constructor:
data = new ArrayList<String>();
and insertion would change to
data.add(value);
you can change your constructor code as (String array max length can be taken as input parameter):
public testsort()
{
data = new String[10];
length = 0;
}
But if you are not sure with the size of array you can use ArrayList.
You are getting exception because you are comparing with data[j+1] that is still null.
first time when you call
t.i("abc");
there is only one reference in data array that is pointing to String literal "abc" and that is at index 0. index 1 is still referring to null.
first String is already sorted so no need to sort that. if you are having more than one string then you should call setSorted() method.
to solve this you can put your condition in loop as:
if((data[j] != null && data[j+1] != null) &&(data[j].compareTo(data[j + 1]) > -1))
A working example but still: use a List and life is much easier :-)
public class Test {
private int length;
private String[] data;
public Test(int arrayLength) {
// INITIALIZE YOU ARRAY --> No NULLPOINTEREXCEPTION!
data = new String[arrayLength];
length = 0;
}
public void i(String value) {
data[length] = value;
length++;
}
public void setSorted() {
for (int j = 0; j < data.length - 1; j++) {
if (data[j].compareTo(data[j + 1]) > -1) {
String temp = data[j];
data[j] = data[j + 1];
data[j + 1] = temp;
}
}
for (String s : data) {
System.out.println(s);
}
}
public static void main(String[] args) {
Test t = new Test(5);
t.i("bbb");
t.i("aaa");
t.i("ccc");
t.i("zzz");
t.i("ddd");
// USE SETSORTED HERE --> else you fill your array with the same elements
t.setSorted();
}
}
The variable 'data' is null since it is nowhere initialized hence giving null pointer exception. Since 'data' is an array and as per the rule whenever an array is defined, it has to be of defined length. for e.g if we consider your case. 'data' can be initialized as :-
String[] data = new String[any numerical value]
the numerical value will be its length i.e. the maximum number of elements it can hold.
Secondly, as per your program statement :-
data[length] = value;
is trying to assign value at data's [length] index which is completely wrong since you haven't defined the length therefore how could you guess the index's value. Therefore your this approaoch is logically wrong.
For such situation i.e. whenever we're unaware about the length of the array, use of ArrayList is suggested. Therefore your program can be re-written by two ways:-
1) Either define the length of the array
String[] data = new String[n];
where n ranges from at least 1 to any positive integer.
2) By using ArrayList
public class Main {
List<String> data;
public Main(){
data = new ArrayList<String>();
}
public static void main(String... q){
Main m = new Main();
m.insertData("abc");
m.insertData("zxy");
m.insertData("aab");
m.insertData("aaa");
m.showData();
}
public void insertData(String str){
data.add(str);
Collections.sort(data);
}
public void showData(){
if(data!=null && !data.isEmpty()){
for(String s : data){
System.out.println(s);
}
}
}
}
output:-
aaa
aab
abc
zxy
Hope this helps.
as Mnementh suggested, the reason for NPE is that you have created the field data of type String[] but you never initialized it.
Other answers have provided every reason on why your code throwing ugly errors; I have just improved your code by replacing your String[] with List<String> so you don't have to worry about the size of your array anymore.
Sorting is also simplified now using Collections.sort().
have a look,
class test1 {
public static void main(String[] args) {
Test sorting = new Test();
sorting.input("abc");
sorting.input("cba");
sorting.input("aab");
sorting.setSorted();
}
}
class Test {
private List<String> data = new ArrayList<String>();
public void input(String value) {data.add(value);}
public void setSorted() {
Collections.sort(data);
for (String current : data) {
System.out.println(current);
}
}
}
if you are using Java 8, then you can use Arrays.parallerSort(), it performs sorting the same way as Collection.sort but with a parallel implementation.
Current sorting implementations provided by the Java Collections Framework > (Collections.sort and Arrays.sort) all perform the
sorting operation sequentially in the calling thread. This enhancement
will offer the same set of sorting operations currently provided by
the Arrays class, but with a parallel implementation that utilizes the
Fork/Join framework. These new API's are still synchronous with regard
to the calling thread as it will not proceed past the sorting
operation until the parallel sort is complete.
to implement it, replace Collections.sort with Arrays.parallelSort in the above code,
Replace,
Collections.sort(data);
with,
Arrays.parallelSort(data.toArray(new String[data.size()]));
Good day,
Here is my code:
public class ArrayDirectory implements Directory {
private int allocatedSize = 0;
public Entry[] entryDirectory = new Entry[allocatedSize];
#Override
public void addEntry(Entry newEntry) {
newEntry = findFreeLocation();
entryDirectory = Arrays.copyOf(entryDirectory,
entryDirectory.length + 1);
}
private Entry findFreeLocation() {
Entry returnedEntry = new Entry();
for (int i = 0; i < entryDirectory.length; i++) {
if (entryDirectory[i] == null) {
break;
}
returnedEntry = entryDirectory[i];
}
return returnedEntry;
}
I've made the size of the entryDirectory dynamic; it increments each time the addEntry method is used. However, when I am trying to call a method of an entry object from the entryDirectory array, a NullPointerException is thrown.
public static void main(String[] args) {
ArrayDirectory d = new ArrayDirectory();
d.addEntry(new Entry("Jack", "Jones", 1234));
d.addEntry(new Entry("Brad", "Jones", 1234));
d.addEntry(new Entry("Olga", "Jones", 1234));
System.out.println(d.entryDirectory[0].getInitials());
}
Here is the getInitials() method of the Entry object.
public Entry(String surname, String initials, int extension){
this.surname = surname;
this.initials = initials;
this.extension = extension;
}
public String getInitials() {
return initials;
}
You never assign anything as element of your array entryDirectory, so NullPointerException arises when you try to invoke getInitials() on null-value object entryDirectory[0].
Remember that if you use Arrays.copyOf(),
for any indices that are valid in the copy but not the original, the
copy will contain null
See Arrays javadoc
In addition to Philip Voronov's answer, your findFreeLocation method is also implemented incorrectly. Assuming null means an absence of value, the proper implementation should be like this:
private int findFreeLocation() {
for (int i = 0; i < entryDirectory.length; i++) {
if (entryDirectory[i] == null) {
return i
}
}
return -1;
}
You can then use it like this:
public void addEntry(Entry newEntry) {
int loc = findFreeLocation();
if (loc >= 0) {
entryDirectory[loc] = newEntry;
} else {
entryDirectory = Arrays.copyOf(entryDirectory, entryDirectory.length + 1);
entryDirectory[entryDirectory.length - 1] = newEntry;
}
}
That said, I highly suggest you use a built-in collection, like ArrayList, to handle automatically resizing arrays. They are much easier to use, and their performance is also better (increasing the array size by one means you have to resize every time an item is added, in comparison to ArrayList's implementation, which doubles the size every time it fills up).