Java - Why am I getting this NullPointerException? - java

I don't understand why this is giving me a null pointer exception when I try to add a value to the a1[i] array.
public class Array {
String text;
int total = 0, count = 0;
Array[] a1 = new Array[100];
Scanner scan = new Scanner(System.in);
public void setData() {
int i=0;
System.out.println(a1.length);
do {
System.out.println("Enter some data: ");
text = scan.next();
if (text.equals("end"))break;
a1[i].text = text; //I get a null pointer exception here. Not sure why.
i++;
} while (true);
}

Everything initialized in the a1 array is null. You'd have to put a new instance of Array() in there before doing anything with the member methods.
What this translates to: Every time you want to do something with a1[i], you'd have to have a new instance of Array in there first.
Example:
for(int i = 0; i < n; i++) {
a1[i] = new Array();
}

Because there isn't an object stored at a1[i]. What you're essentially saying at that line is:
null.text = text
which will break every time

You are getting a null-pointer exception, because you have allocated the space for 100 array elements, but you still need to initialize them:
So before accessing a1[i].text you need to initialize it by calling a1[i] = new Array()
Also I am quite sure, that you actually wanted to create some other kind of object, not Array. Array the class you are currently writing, as I understand, so you probably want to have multiple Strings, e.g. String[].
I recommend to you to use a LinkedList instead.

Array[] a1 = new Array[100]; //here you just create an array of references to objects which are set to null
a1[i].text = text; //before this line you should assign to a1[i] a reference to Array object for example a1[i] = new Array();

Related

changes to a variable dont remain outside the loop & variables dont inherit to other classes

What I want to do: read strings from keyboard using Scanner until specific string is used to break the infinite loop. save them in an arrayList, then pass them into an array with its length beeing the number of the iteration of the loop
public class InputReader {
ArrayList<Integer> list = new ArrayList<>(0);
int arrayLength;
String readInput;
Scanner ir = new Scanner(System.in);
void readInput() {
for (int m=0; ;m++) {
readInput = ir.nextLine();
if ("q".equals(readInput)) {
//problem: arrayLength does not have the value of m outside the loop
arrayLength = m;
break;
}
System.out.println("arrayLength: "+arrayLength);
intInput = Integer.parseInt(readInput);
list.add(intInput);
}
}
int[] array = new int[arrayLength];
}
}
Inside the loop arrayLength works perfectly but outside the loop it has no value as I initialized it without value. Because of this,
System.out.println("array.length: "+array.length);
always returns 0 and the compiler returns this error:
java.lang.ArrayIndexOutOfBoundsException: Index 0 out of bounds for length 0
when I try to save integers inside the array.
1) How can I make the changes to the variable stay outside the loop?
2) Weird observation A:
int[] array = new int[list.size()];
returns the same error despite list.size() having the right value even outside the loop (checked by printing it).
And B: The code works if I create my array inside another method instead of inside the class and then use it in the method, but this way I cannot use it in my other classes despite using inheritance or parameters.
void giveOutput() {
int[] array = new int[list.size()];
public void giveOutput () {
System.out.println("list.size()"+list.size());
System.out.println("array.length:"+array.length);
for (int n=0; n<list.size(); n++) {
array[n] = list.get(n);
System.out.print("array["+n+"]:"+array[n]+" ");
}
}
}
this creates a working array but I cant hand it over to my Minsort extends InputReader subclass where it is sorted which leads to question number
3) How to use variables initialized in methods in other classes? This way my program could work too.
(I am a bloody beginner, started seriously working with java yesterday, my first succesful project was a Minsort-Algorithm I wrote from scratch so please have mercy. And thanks in advance.)
The array array is initialized when an object of the type InputReader is instantiated, not after the readInput() method is run.
In other words, array is always initialized when you use new InputReader(), not after the readInput() method is run. That means that the arrayLength variable has not yet been modified at the moment when array is created, so the default value for an int is used, which is 0.
Try this:
public static class InputReader {
ArrayList<Integer> list = new ArrayList<>(0);
int arrayLength;
String readInput;
Scanner ir = new Scanner(System.in);
int[] array;
void readInput() {
for (int m=0; ;m++) {
readInput = ir.nextLine();
if ("q".equals(readInput)) {
//problem: arrayLength does not have the value of m outside the loop
arrayLength = m;
break;
}
int intInput = Integer.parseInt(readInput);
list.add(intInput);
}
System.out.println("arrayLength: "+arrayLength);
array = new int[arrayLength];
}
}
Also, your System.out.println("arrayLength: "+arrayLength); always returned 0 because the arrayLength changes only when q is pressed.
To answer your third point: You could create a getter function in the class InputReader. For example:
public int[] getArray() {
return array;
}
As a side-note: It is very good practice to have your instance variables be declared with a private access modifier, and to then create public getter and setters. This is called Encapsulation, and is an OOP principle (my advice is that you google the OOP principles).
More info about getters and accessors here: Why use getters and setters/accessors?

How to use a for loop to set String variable mixed with numbers to ""?

I have inherited a Java program which I need to change. In one part of the code, I see I have created over 1000 String variables such as:
String field01
String field02
...
String field1000
I want to make a for loop to set all of the mentioned variables to "", but I am having issues with building a correct format for the for loop.
How do I create field+(i) in the for loop to set field01 to "" and the rest?
A for loop... Well, you could make this an array, but there's not really any way to make this into a for loop without an array.
Here's an example with one:
String[] test = new String[1000];
for (int number; numer < 1000; number++){
test[number] = "";
}
You have to use Reflection for doing the same.
class Test {
String field1
String field2
...
String field1000
}
public class FieldTest {
public static void main(String args[]) {
Test t = new Test();
Class cls = t.getClass();
for(int i=0 ; i<=1000; i++){
Field f1 = cls.getField("field"+i);
f1.set(t, "");
}
}
}
You can't really do this in Java. An alternative is to make a String array where the index of the array is the number of the variable that you want. So field01 would be stored in your string array at index 1.
First, create an array. Second, use Arrays.fill:
String[] fields = new String[1000];
Arrays.fill(fields, "");
Later you can access or modify individual variables by indices like fields[index].
Creating 1000 variables with similar names is not how people program in Java.
I know it is not the exact answer, but may help you.or you will need to use reflection.
Map<String, String> container = new HashMap<String, String>();
for (int i = 0; i <1000; i++) {
container.put("field"+ i, "\"\" ");
}

Null pointer exception in array initialized to null [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
This is the following code. I have to make the array null for a purpose, then when I initialize the array components to 1, it shows null pointer exception. How to handle this?
public static void main(String[] args) {
double[] a;
a=null;
if(a==null)
for(int i=0;i<12;i++)
a[i]=1;
}
You need to create an array object and assign it to the array variable before trying to use the variable. Otherwise you are creating the very definition of a NullPointerException/NPE: trying to use (dereference) a reference variable that refers to null.
// constant to avoid "magic" numbers
private static final int MAX_A = 12;
// elsewhere in code
if (a == null) {
a = new double[MAX_A]; // you need this!
for (int i = 0; i < a.length; i++) {
a[i] = 1.0;
}
}
a[i]=1 // That's the problem.
You are trying to assign a value, without actually allocating memory (aka, not initializing). Indirectly you are trying to invoke a operation on NULL object which obviously results in Null Pointer Exception.
So
if(a == null){
a = new double[12];
//other for loop logic
}
will solve the problem. 12 is the size of the array (The number of double value it can hold/store).
You have to create the array before initialization -
double[] a;
a=null;
if(a==null){
a = new double[12];
for (int i = 0; i < a.length; i++) {
a[i] = 1.0;
}
}
Since double array a is null when you are trying to access the array element like this -
a[i]=0;
It produces NullPointerException.
At the first place why don't you make it NULL while declaring the variable double[] a = null;
The reason why you are getting NullPointer is because you are trying to access it when it is NULL a[i]=1;. This is as good as String name = null; name.toString(); You are doing some operation on an NULL value so getting NullPointer.
Just initialize it and then try to access it and you will not get NullPointer. This is like you should first allocate some memory and then try to access the memory location, when no memory is allocated, you will get NullPointer which tells you that there is no memory allocated yet. Hope this helps.

Why is Station Object Null inside the For-Each Loop?

I am writing a basic program that iterates through an array of objects. I am then making a for-each loop and setting the values of each object in the array from user input. However, I am getting a null-pointer exception on the object I am using to store the value of the object array.
Here is my code:
import javax.swing.*;
public class Calculation {
public static Stations[] createStationArray(){
int numOfStations;
String string = JOptionPane.showInputDialog(null,"How many stations are there?");
numOfStations = Integer.parseInt(string);
Stations[] stations = new Stations[numOfStations];
JOptionPane.showMessageDialog(null, stations.length);
return stations;
}
public static void main(String[] args){
Stations[] stations;
stations = createStationArray();
System.out.println("stations array value" + stations);
for(Stations station : stations)
{System.out.println("station variable value" + station);
int stationNum = 1;
double amountOfWaste;
station.setStationNum(stationNum);
String string = JOptionPane.showInputDialog(null,"What is this Station's waste amount?");
amountOfWaste = Double.parseDouble(string);
station.setWaste(amountOfWaste);
System.out.println("Station " + station.getStationNum() + " has a waste amount of " + station.getWaste());
}
}
}
I am having issues in the for-each loop with the variable "station".
It is supposed to be the current object in the array list. However, I am getting a null-pointer exception. Here is the console output.
stations array value[LStations;#28787c16
Exception in thread "main" java.lang.NullPointerException
at Calculation.main(Calculation.java:27)
station variable value null
erException
at Calculation.main(Calculation.java:27)
You created an array of stations, but did not populate it. So when you loop over the array, every entry is still null.
You need to instantiate the Stations before calling methods on it. Try adding this inside createStationArray() after instantiating the Stations array:
for (int i = 0; i < numOfStations; i++)
stations[i] = new Stations();

How come the array of objects I'm creating is a set of nulls?

So I'm creating a class called dicegame. Here's the constructor.
public class dicegame {
private static int a, b, winner;
public dicegame()
{
a = 0;
b = 0;
winner = 2;
}
And now in the main, I'm creating an array of this object (I called it spaghetti for fun).
public static void main(String[] args)
{
dicegame[] spaghetti = new dicegame[10];
spaghetti[1].roll();
}
But when I try to do anything to an element in the array, I'm getting the NullPointerException. When I tried to print one of the elements, I got a null.
You created an array, but you have to assign something (e.g. new dicegame()) to each element of the array.
My Java is slightly rusty, but this should be close:
for (int i=0; i<10; i++)
{
spaghetti[i] = new dicegame();
}
new dicegame[10]
just creates an array with 10 empty elements. You still have to put a dicegame in each element:
spaghetti[0] = new dicegame();
spaghetti[1] = new dicegame();
spaghetti[2] = new dicegame();
...
You need spaghetti[1]=new dicegame() before you call roll() on it.
Right now you are allocating an array,but don't. Place any objects in this array, so by default java makes them null.
1.you have just declared the array variable but not created the object yet. try this
2.you should start index with zero not with one.
dicegame[] spaghetti = new dicegame[10]; // created array variable of dicegame
for (int i = 0; i < spaghetti.length; i++) {
spaghetti[i] = new dicegame(); // creating object an assgning to element of spaghetti
spaghetti[i].roll(); // calling roll method.
}
Firstly,you should create object for every spaghetti input of yours.
You can start with whatever value you want. Just be sure that the size of array is matched accordingly so that you won't get ArrayIndexOutOfBounds Exception.
So,if you wanted to start with 1 and have 10 objects of the class dicegame,you will have to assign the size of the array as 11(since it starts from zero).
your main function should be like :
public static void main(String[] args)
{
dicegame[] spaghetti = new dicegame[11];
//the below two lines create object for every spaghetti item
for(int i=1;i<=11;i++)
spaghetti[i]=new dicegame();
//and now if you want to call the function roll for the first element,just call it
spaghetti[1].roll;
}

Categories

Resources