Getting NullPointer Exception when declaring LinkedBlockingQueue<String> - java

This is the code I have. I have getting Null Pointer Exception in the last line of the constructor (workerQueue[i] = new LinkedBlockingQueue(100);):
public class QueueThreadPool {
private BlockingQueue<String>[] workerQueue;
private Thread[] workerThreads;
private int numQueues;
private int numThreads;
public QueueThreadPool(int numThreads, int numQueues) {
this.numQueues = numQueues;
this.numThreads = numThreads;
for(int i=1; i<=numQueues; i++){
workerQueue[i] = new LinkedBlockingQueue<String>(100);
}
}
public static void main(String args[]){
System.out.println("Start...");
new QueueThreadPool(50, 11);
System.out.println("End...");
}
Please help!
Thanks!!

Array workerQueue is not instantiated which you need to do.
private BlockingQueue<String>[] workerQueue;
workerQueue is a reference of BlockingQueue<String>[] type, not a Object.
But also you cannot create a generic array of BlockingQueue<String>. Instead of that create a List of BlockingQueue<String>. Ex -
private List<BlockingQueue<String>> workerQueue= new ArrayList<>();
you can also create the list Object at constructor.
private List<BlockingQueue<String>> workerQueue= new ArrayList<>();
public QueueThreadPool(int numThreads, int numQueues) {
this.workerQueue = new ArrayList<>(numQueues); // <-- initialize the field.
this.numQueues = numQueues;
this.numThreads = numThreads;
...

You haven't initialized workerThreads. You have to do something like workerQueue= new BlockingQueue<String>[numQueues];

Two problems in the code: the field need to be initialized, the loop should go from 0 to the array-size's - 1. Here is how the fixed code should look like:
public class QueueThreadPool {
private BlockingQueue<String>[] workerQueue;
private Thread[] workerThreads;
private int numQueues;
private int numThreads;
public QueueThreadPool(int numThreads, int numQueues) {
this.workerQueue = new BlockingQueue<String>[numQueues] // <-- You need to initialize the field.
this.numQueues = numQueues;
this.numThreads = numThreads;
for(int i=0; i < numQueues; i++){ // <-- Indexing into arrays goes from 0 to size-1 (inclusive).
workerQueue[i] = new LinkedBlockingQueue<String>(100);
}
}

Related

Method that checks if the method was already executed with that input

public class CatalanNumbers {
private int howManyVariaties;
private int catalanNumber;
private int catalanNumber;
public int catalan(int a) {
if (Method was never executed with that input) {
howManyVariaties++;
int catalanNumber = 0;
for (int i= 0; i < n; i++) {
catalanNumber += catalan(i) * catalan( n- 1 -i);
return catalanNumber
To sum it up I only want to check how the maximum stack depth is.
Can someone help me?
Add a Set to your class that keeps track of what input was used and check that set inside the method
public class CatalanNumbers {
private int howManyVariaties;
private int catalanNumber;
private int catalanNumber;
private Set<Integer> alreadyHandled = new HashSet<>();
public int catalan(int a) {
if (alreadyHandled.add(a)) {
//rest of code
}
}
//...
}

How to read copy the array with the array from another class? [In loading file]

I want to create a game and I need to read file from the notepad
when I use my loadfile.java alone, it work very well. Then, I would like to copy my data into datafile.java as it will be easier for me to do the fighting scene. However, I can't copy the array in my loadfile.java to the datafile.java and I don't understand why.
import javax.swing.*;
import java.io.*;
import java.util.Scanner;
public class loadfile
{
static String filename = "Save.txt";
static int size = 4;
static int s;
static int[] number;
static String[] line;
private static void load() throws IOException
{
BufferedReader reader = new BufferedReader(new FileReader(filename));
while (reader.readLine()!= null)
{
size++;
}
size -= 4;
reader.close();
line = new String[size];
number = new int[size];
BufferedReader reader2 = new BufferedReader(new FileReader(filename));
for (int i = 0; i < size; i++)
{
line[i] = reader2.readLine();
}
reader2.close();
for (int i = 4; i < size; i++)
{
number[i] = Integer.parseInt(line[i]);
}
}
public static String[] getData()
{
return line;
}
public static int[] getNumber()
{
s = size - 4;
int[] num = new int[s];
for (int i = 0; i < s; i++)
{
num[i] = number[i+4];
}
return num;
}
public static int getDataSize()
{
return size;
}
public static int getNumberSize()
{
return size - 4;
}
This is my loadfile.java
I use the file with 4 names and 9 * n int in the notepad as I want to check whether I have the character first before I read the file. However, before I can handle this problem, I got another problem that I can't copy the array into my datafile.java
The datafile.java is separate with two constructor. One is for Starting the game and one is for loading the data. The constructor with the (int num) is the problem I have. First, I would like to show the java first:
import java.util.Arrays;
import java.io.*;
public class datafile
{
private static String[] data;
private static int[] number;
private static String[] name;
private static int[] a, d, s;
private static int[] hp, maxhp;
private static int[] mp, maxmp;
private static int[] lv, exp;
public datafile()
{
initialization();
name[0] = "Pet";
a[0] = 100;
d[0] = 100;
s[0] = 100;
hp[0] = 500;
mp[0] = 500;
maxhp[0] = 500;
maxmp[0] = 500;
exp[0] = 100;
lv[0] = 1;
}
public datafile(int num) throws IOException
{
initialization();
loadfile l = new loadfile();
for (int i = 0; i < l.getNumberSize(); i++)
{
number[i] = l.getNumber()[i];
}
for (int i = 0; i < l.getDataSize(); i++)
{
data[i] = l.getData()[i];
}
for(int i = 0; i < 4; i++)
{
name[i] = data[i];
}
for(int i = 0; i < 4; i++)
{
a[i] = number[1+(i*9)];
d[i] = number[2+(i*9)];
s[i] = number[3+(i*9)];
hp[i] = number[4+(i*9)];
mp[i] = number[5+(i*9)];
maxhp[i] = number[6+(i*9)];
maxmp[i] = number[7+(i*9)];
lv[i] = number[8+(i*9)];
exp[i] = number[9+(i*9)];
}
}
public static String getName(int n)
{
return name[n];
}
public static int getAttack(int n)
{
return a[n];
}
public static int getDefense(int n)
{
return d[n];
}
public void initialization()
{
name = new String[3];
a = new int[3];
d = new int[3];
s = new int[3];
hp = new int[3];
mp = new int[3];
maxhp = new int[3];
maxmp = new int[3];
lv = new int[3];
exp = new int[3];
}
public static void main (String[] args) throws IOException
{
new datafile(1);
}
}
When I run the program, the debugging state this line
data[i] = l.getData()[i];
as an error
I don't know what wrong with this line and I tried so many different ways to change the way the copy the method. However, it didn't work
The error says this:
Exception in thread "main" java.lang.NullPointerException
at datafile.<init>(datafile.java:38)
at datafile.main(datafile.java:92)
I hope you guys can help me with this problem because I don't want to fail with my first work
in your datafile(int num)
you call
loadfile l = new loadfile();
but you never call the load() method on you loadfile
l.load();
Edit: my bad, I didn't see your initialization method, but regardless, I'm going to stick with my recommendation that you radically change your program design. Your code consists of a kludge -- you've got many strangely named static array variables as some kind of data repository, and this suggests that injecting a little object-oriented design could go a long way towards creating classes that are much easier to debug, maintain and enhance:
First I recommend that you get rid of all of the parallel arrays and instead create a class, or likely classes, to hold the fields that need to be bound together and create an ArrayList of items of this class.
For example
public class Creature {
private String name;
private int attack;
private int defense;
// constructors here
// getters and setters...
}
And elsewhere:
private List<Creature> creatureList = new ArrayList<>();
Note that the Creature class, the repository for some of your data, should not be calling or even have knowledge of the code that loads the data, but rather it should be the other way around. The class that loads data should create MyData objects that can then be placed within the myDataList ArrayList via its add(...) method.
As a side recommendation, to help us now and to help yourself in the future, please edit your code and change your variable names to conform with Java naming conventions: class names all start with an upper-case letter and method/variable names with a lower-case letter.

Why does this Java program work counter to my expectations?

Why does this program work counter to my expectations?
I expect: 1 50 47 50
I get: 0 50 0 50
class Poppet {
int i;
Poppet(int i) {
i = i;
}
}
class Ideone
{
private final int i = 50; // Initialized final
private final int j; // Blank final
private final Poppet p; // Blank final reference
// Blank finals MUST be initialized in the constructor:
public Ideone() {
j = 1; // Initialize blank final
p = new Poppet(1); // Initialize blank final reference
System.out.println(p.i);
}
public Ideone(int x) {
j = x; // Initialize blank final
p = new Poppet(x); // Initialize blank final reference
System.out.println(p.i);
}
public static void main (String[] args)
{
Ideone t = new Ideone();
System.out.println(t.i);
Ideone r = new Ideone(47);
System.out.println(r.i);
}
}
Can you please explain why?
Change:
Poppet(int i) {
i = i;
}
to:
Poppet(int i) {
this.i = i;
}
by doing i = i you're assigning the method argument to itself while what you really want to do is to assign it to the class member variable.
Local variable shadowing, as described in JLS 6.4.1.
If you want to set the instance variable i, you have to prefix it as in this.i.
class Poppet {
int i;
Poppet(int i) {
this.i = i;
}
}

How to put array in an object in Java?

I am trying to clone an array and return as an object, not an array type.
z
public IntVector clone()
{
IntVector cloneVector = new IntVector(3);
int[] newItems = new int[10];
for(int i=0 ; i<itemCount_; ++i)
{
newItems[i] = items_[i];
}
cloneVector = newItems; // is there a way to do something like this??
return cloneVector;
}
Main method looks like this
public static void main(String[] args)
{
IntVector vector = new IntVector(5);
vector.push(8);
vector.push(200);
vector.push(3);
vector.push(41);
IntVector cloneVector = vector.clone();
}
*there are two other methods which makes an array:IntVector() and puts value into array:push()
Declare a new constructor for IntVector which takes an int array and a count:
IntVector(int[] data, int n) {
items_ = data.clone();
itemCount_ = n;
}
Then you can write clone like this:
public IntVector clone() {
return new IntVector(items_, itemCount_);
}
You can make that new constructor private if you like, so only clone can use it.

java: newbie on indexing object arrays

I wish to create a java method that returns an array of type: ABCout, where class ABCout is defined as:
public class ABCout {
public int numOut;
public double[] myArray;
}
and the java method is:
public ABCout[] GetABC( double myInput ) throws Exception {
ABCout[] userABC = new ABCout[3];
userABC[0].numOut = 10;
userABC[0].myArray = new double[1];
userABC[0].myArray[0] = myInput;
/* here I only fill the 0'th element, but once working I will fill the others */
return userABC;
}
but I'm getting the error: java.lang.NullPointerException : null
Anyone see what I'm doing wrong?
You initialized the array, but not the objects in it. You probably need to do:
ABCout[] userABC = new ABCout[3];
for (int i = 0; i < userABC.length; ++i) {
userABC[i] = new ABCout();
}
Also, you need to instantiate myArray:
public class ABCout {
public int numOut;
public double[] myArray;
public ABCout() {
myArray = new double[10];
}
}
You need to instantiate the ABCout object you store in the array.
public ABCout[] GetABC( double myInput ) throws Exception {
ABCout[] userABC = new ABCout[3];
userABC[0] = new ABCout(); // instantiate
userABC[0].numOut = 10;
userABC[0].myArray = new double[1];
userABC[0].myArray[0] = myInput;
/* here I only fill the 0'th element, but once working I will fill the others */
return userABC;
}
You're declaring an array of ABCout, but you're trying to access the first element of that array before assigning it.
public ABCout[] GetABC( double myInput ) throws Exception {
ABCout[] userABC = new ABCout[3];
userABC[0] = new ABCout();
userABC[0].numOut = 10;
userABC[0].myArray = new double[1];
userABC[0].myArray[0] = myInput;
return userABC;
}
//add this
userABC[0] = new ABCount();
userABC[0].numOut = 10;
userABC[0].myArray = new double[1];
userABC[0].myArray[0] = myInput;
Although you definetly need to study some object oriented coding before doing + you should read some basic java tutorial as well
As others have stated, there was no instantiation of the 0th object and therefore you had a runtime error. You could also do this:
public ABCout[] GetABC( double myInput ) throws Exception {
ABCout[] userABC = new ABCout[3];
ABCout current = new ABCout();
current.numOut = 10;
current.myArray = new double[1];
current.myArray[0] = myInput;
userABC[0] = current;
return userABC;
}

Categories