Java - NullPoinerException Array of objects [closed] - java

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
Can't figure this out, I've created a simple class of coordinates to hold x and y ints. In another class I have a global array of Coordinates declared called "ords". In my loop I'm adding Coordinates. When trying to use method getX() and getY() from the Coordinates class in my getaction method, I get a null pointer exception. I'm sure the objects are not null, but I still can't figure out whats going wrong. Any help appreciated.
import java.util.*;
import org.w2mind.net.*;
import java.io.Serializable;
public class ConorsMind implements Mind
{
int [][] surroundings = new int [12][16];
Coordinates [] ords = new Coordinates [192];
int currentX;
int currentY;
//====== Mind must respond to these methods: ==========================================================
// newrun(), endrun()
// getaction()
//======================================================================================================
public void newrun() throws RunError
{
}
public void endrun() throws RunError
{
}
private void formTwoDimmensional(int [] someArray)
{
int counter = 0;
int n=0;
for(int i = 0; i < 15; i++)
{
for(int z = 0; z < 12; z++)
{
surroundings[z][i] = someArray[counter];
if(surroundings[z][i] ==0) {
currentX=z;
currentY=i;
}
else if(surroundings[z][i]==4){
ords[n]= new Coordinates(z,i);
n++;
}
System.out.print(z+" , "+i+": "+surroundings[z][i]);
System.out.println();
counter++;
}
}
}
public Action getaction ( State state )
{
String s = state.toString();
String[] x = s.split(",");
int act =MinerWorldUpdated.NO_ACTIONS;
int counter = 0;
int [] surround = new int [192];
//in this way user will have ability to see what surrounds him
for(int i = 11; i < 203; i++)
{
surround[counter] = Integer.parseInt(x[i]);
counter++;
}
formTwoDimmensional(surround);
int [] response = new int [x.length];
for(int i = 0; i < x.length; i++)
{
response[i] = Integer.parseInt ( x[i] );
}
System.out.println("Current position: "+currentX+" ,"+currentY);
int coalX=ords[0].getX();
int coalY=ords[0].getY();
System.out.println("Coal position: "+coalX+" ,"+coalY);
if(coalX != 0 && coalY !=0)
{
if(coalX>currentX)
{
act=MinerWorldUpdated.ACTION_DOWN;
}
else if(coalY<currentY)
{
act=MinerWorldUpdated.ACTION_LEFT;
}
else if(coalX<currentX)
{
act=MinerWorldUpdated.ACTION_DOWN;
}
else if(coalY<currentY)
{
act=MinerWorldUpdated.ACTION_LEFT;
}
}
String a = String.format ( "%d", act );
return new Action ( a );
}
}
class Coordinates implements Serializable
{
private int x;
private int y;
public Coordinates(int x1, int y1)
{
x=x1;
y=y1;
}
public int getX(){
return x;
}
public int getY(){
return y;
}
}
Error is as follows:
java.lang.NullPointerException
at ConorsMind.getaction(ConorsMind.java:146)
The error is stemming from the following two lines:
int coalX=ords[0].getX();
int coalY=ords[0].getY();
I am calling formTwoDimensional() and its working perfectly, the ords objects are being created successfully and are not null as testing with System.out.println(ords[n].getX()) is printing the expected result when placed in my else if(surroundings[z][i]==4) block.

You need to make sure that you're calling formTwoDimensional(). If you are indeed, then it's likely that you're not ever getting into your else if block in the nested for loop, and hence ords[0] is never actually being set, so when you try to access it, it's null.
The other thing to do, if you don't want to post the rest of your code, is to add some more debugging code. See below the boolean zero_pos_set. But make sure that you see the print "Zero pos set" before your program crashes. My bet is that you don't.
public class ConorsMind implements Mind
{
int [][] surroundings = new int [12][16];
Coordinates [] ords = new Coordinates [192];
boolean zero_pos_set = false;
private void formTwoDimmensional(int [] someArray)
{
int counter = 0;
int n=0;
for(int i = 0; i < 15; i++) {
for(int z = 0; z < 12; z++) {
surroundings[z][i] = someArray[counter];
if(surroundings[z][i] ==0) {
currentX=z;
currentY=i;
} else if(surroundings[z][i]==4) {
zero_pos_set = true;
ords[n]= new Coordinates(z,i);
n++;
}
counter++;
}
}
}
public Action getaction ( State state ) {
if(zero_pos_set) {
System.out.println("Zero pos set!");
}
int coalX=ords[0].getX();
int coalY=ords[0].getY();
System.out.println("Coal position: "+coalX+" ,"+coalY);
return new Action ( a );
}
}

Based on all of the debugging information posted within this thread, it seems that in your getaction() function, you're being passed some state, that doesn't contain 4.
When you parse this information and pass it to formTwoDimensional(), you will never reach the else if block, and so ords[0], or any other ords[n], will never be set.
As a result, when you try to access ords[0] back in your getaction() function, you actually get null, and hence your NullReferenceException.

It's an order of operations issue.
If you never make a call to formTwoDimmensional(), you'll never initialize anything inside of your array. Be sure you're calling that first.
The actual NPE happens when you attempt to call coalX=ords[0].getX();, which won't work if ords[0] is null.

Related

System.out.println doesn't show text in console (IntelliJ)

I am writing a program which part is presented below:
public class Portal {
private String name;
private int[] positions; // positions of "ship"
private static int moves = 0; // moves made by player to sink a ship
public static int shot; // the value of position given by player
private int hits = 0; // number of hits
private int maxSize = 4; // max size of ship (the size will be randomized)
int first; // position of 1st ship block
int size; // real size of ship (randomized in setPortal method)
public void checkIfHit(){
for (int i : positions){
if (i == shot){
System.out.println("Hit confirmed");
hits++;
} else if (hits == positions.length){
System.out.println("Sunk");
} else {
System.out.println("Missed it");
}
}
moves++;
}
public void setPortal(){
size = 1 + (int)Math.random()*maxSize;
for (int i = 0; i < size - 1; i++){
if (i == 0){
positions[i]= 1 + (int)Math.random()*positions.length;
first = positions[i];
System.out.println(positions[i]);
continue;
}
positions[i]= first + 1;
System.out.println(positions[i]);
}
}
}
public class Main{
public static void main(String[] args){
// write your code here
Portal p1 = new Portal();
p1.setPortal();
}
}
code is split in two Java .class files.
The problem I'm dealing with is that using p1.setPortal(); doesn't show up text in IntelliJ console. The program works though and returns 0.
I don't have such problem in another program when I've put System.out.println in method other than main (also in separate class file).
What may be the cause of such issue?
It should properly throw an exception, because you forgot to initialize the integer array.
Have a look at this thread: Do we need to initialize an array in Java?
The Java's default value is null for an integer array. So your for wont even loop trough. The only thing that wonders me is why there is no exception..

Java - I need to print this string of characters to a string I can use out of loop

I have been buried in this assignment for 2 days chasing down rabbit holes for possible solutions. I am beginner Java, so I am sure this shouldn't be as difficult as I am making it.
I trying to program the infamous Java Bean Machine... My professor want the Class Path to return a String Variable that only holds "R" "L" . to represent the path of the dropped ball.
Each ball should have its own Path... I can get the path... but I can not get the path to print in a string outside of the for/if statement.
Here are his instructions... in case you can see if I am interpreting this incorrectly.
Please help!! Thank you in advance for sifting through this....
my code so far ******** i have updated the code to reflect the suggestions.. Thank you... ***************** New problem is it repeats the series of letters in a line... I only need a string of 6 char ....(LRLLRL)
public class Path {
StringBuilder myPath;
public Path() {
myPath = new StringBuilder();
}
void moveRight() {
myPath.append("R");
}
void moveLeft() {
myPath.append("L");
}
public void fallLevels(int levels) {
levels = 6;
for (int i = 0; i < (levels); i++) {
if (Math.random() < 0.5) {
this.moveRight();
} else {
this.moveLeft();
}
}
}
public String getPath() {
System.out.print(myPath.toString());
return myPath.toString();
}
}
}
******Thank you all.. this class now returns the correct string for one ball...***************
here is my code so far for multiple balls... I can get a long continuous string of 6 character sequences... I need each sequence to be a searchable string...I am not sure if I need to alter the Path class or if its something in the simulateGame() method. I think I can take it after this hump... Thank you again....
public class BeanMachine {
int numberOfLevels;
int[] ballsInBins;
Path thePath = new Path();
public BeanMachine(int numberOfLevels) {
this.numberOfLevels = 6;
ballsInBins = new int[this.numberOfLevels + 1];
// this.numberOfLevels +
}
public void simulateGame(int number) {
//looping through each ball
for (int i = 0; i < numberOfLevels -1; i++) {
thePath.fallLevels(0);
}
thePath.getPath().toString();
}
*** this isn't the entire code for this class... I have to get this method correct to continue....
Problem with your code:
if (Math.random() < 0.5) {
**loop = this.myPath = "R";**
} else {
**loop = this.myPath ="L";**
}
Change this to:
if (Math.random() < 0.5) {
**loop = this.myPath + "R";**
} else {
**loop = this.myPath + "L";**
}
Just added ** to highlight where there is wrong in your code

From String to Integer Functions

I am trying to write a program that will receive a function as a String and solve it. For ex. "5*5+2/2-8+5*5-2" should return 41
I wrote the code for multiplication and divisions and it works perfectly:
public class Solver
{
public static void operationS(String m)
{
ArrayList<String> z = new ArrayList<String>();
char e= ' ';
String x= " ";
for (int i =0; i<m.length();i++)
{
e= m.charAt(i);
x= Character.toString(e);
z.add(x);
}
for (int i =0; i<z.size();i++)
{
System.out.print(z.get(i));
}
other(z);
}
public static void other(ArrayList<String> j)
{
int n1=0;
int n2=0;
int f=0;
String n= " ";
for (int m=0; m<j.size();m++)
{
if ((j.get(m)).equals("*"))
{
n1 = Integer.parseInt(j.get(m-1));
n2 = Integer.parseInt(j.get(m+1));
f= n1*n2;
n = Integer.toString(f);
j.set(m,n);
j.remove(m+1);
j.remove(m-1);
m=0;
}
for (int e=0; e<j.size();e++)
{
if ((j.get(e)).equals("/"))
{
n1 = Integer.parseInt(j.get(e-1));
n2 = Integer.parseInt(j.get(e+1));
f= n1/n2;
n = Integer.toString(f);
j.set(e,n);
j.remove(e+1);
j.remove(e-1);
e=0;
}
}
}
System.out.println();
for (int i1 =0; i1<j.size();i1++)
{
System.out.print(j.get(i1)+",");
}
However, for adding and subtracting, since there isnt an order for adding and subtracting, just whichever comes first, I wrote the following:
int x1=0;
int x2=0;
int x3=0;
String z = " ";
for (int g=0; g<j.size();g++)
{
if ((j.get(g)).equals("+"))
{
x1= Integer.parseInt(j.get(g-1));
x2= Integer.parseInt(j.get(g+1));
x3= x1+x2;
z = Integer.toString(x3);
j.set(g,z);
j.remove(g+1);
j.remove(g-1);
g=0;
}
g=0;
if ((j.get(g)).equals("-"))
{
x1= Integer.parseInt(j.get(g-1));
x2= Integer.parseInt(j.get(g+1));
x3= x1-x2;
z = Integer.toString(x3);
j.set(g,z);
j.remove(g+1);
j.remove(g-1);
g=0;
}
g=0;
}
System.out.println();
for (int i1 =0; i1<j.size();i1++)
{
System.out.print(j.get(i1)+",");
}
After this, it prints:
25,+,1,-,8,+,25,–,2,
. What am I doing wrong? Multiplication and dividing seem to be working perfectly
You have 2 problems:
1) g=0; statements after if and else blocks will make you go into an infinite loop.
2) From the output you gave, the first minus (-) is Unicode character HYPHEN-MINUS (U+002D), while the second minus (–) is Unicode character EN DASH (U+2013), so (j.get(g)).equals("-") fails for the second minus as they are not equal.
Going for an answer that doesn't help with your exact specific problem, but that hopefully helps you much further than that.
On a first glance, there are various problems with your code:
Your are using super-short variable names all over the place. That saves you maybe 1 minute of typing overall; and costs you 5, 10, x minutes every time you read your code; or show it to other people. So: dont do that. Use names that say what the thing behind that name is about.
You are using a lot of low-level code. You use a "couting-for" loop to iterate a list (called j, that is really really horrible!) for example. Meaning: you make your code much more complicated to read than it ought to be.
In that way, it looks like nobody told you so far, but the idea of code is: it should be easy to read and understand. Probably you dont get grades for that, but believe me: in the long run, learning to write readable code is a super-important skill. If that got you curious, see if you can get a hand on "Clean code" by Robert Martin. And study that book. Then study it again. And again.
But the real problem is your approach to solve this problem. As I assume: this is some part of study assignment. And the next step will be that you don't have simple expressions such as "1+2*3"; but that you are asked to deal with something like "sqrt(2) + 3" and so on. Then you will be asked to add variables, etc. And then your whole approach breaks apart. Because your simple string operations won't do it any more.
In that sense: you should look into this question, and carefully study the 2nd answer by Boann to understand how to create a parser that dissects your input string into expressions that are then evaluated. Your code does both things "together"; thus making it super-hard to enhance the provided functionality.
You can use the built-in Javascript engine
public static void main(String[] args) throws Exception{
ScriptEngineManager mgr = new ScriptEngineManager();
ScriptEngine engine = mgr.getEngineByName("JavaScript");
String code = "5*5+2/2-8+5*5-2";
System.out.println(engine.eval(code));
}
Primarily Don't Repeat Yourself (the DRY principle). And use abstractions (full names, extracting methods when sensible). Static methods are a bit cumbersome, when using several methods. Here it is handy to use separate methods.
Maybe you want something like:
Solver solver = new Solver();
List<String> expr = solver.expression("5*5+2/2-8+5*5-2");
String result = solver.solve(expr);
A more abstract Solver class would do:
class Solver {
List<String> expression(String expr) {
String[] args = expr.split("\\b");
List<String> result = new ArrayList<>();
Collections.addAll(result, args);
return result;
}
String solve(List<String> args) {
solveBinaryOps(args, "[*/]");
solveBinaryOps(args, "[-+]");
return args.stream().collect(Collectors.joining(""));
}
The above solveBinaryOps receives a regular expression pattern or alternatively simply in some form the operators you want to tackle.
It takes care of operator precedence.
private void solveBinaryOps(List<String> args, String opPattern) {
for (int i = 1; i + 1 < args.length; ++i) {
if (args.get(i).matches(opPattern)) {
String value = evalBinaryOp(args.get(i - 1), args.get(i), args.get(i + 1));
args.set(i, value);
args.remove(i + 1);
args.remove(i - 1);
--i; // Continue from here.
}
}
}
private String evalBinaryOp(String lhs, String op, String rhs) {
int x = Integer.parseInt(lhs);
int y = Integer.parseInt(rhs);
int z = 0;
switch (op) {
case "*":
z = x * y;
break;
case "/":
z = x / y;
break;
case "+":
z = x + y;
break;
case "-":
z = x - y;
break;
}
return Integer.toString(z);
}
}
The above can be improved at several points. But it is readable, and rewritable.
public class Solver {
public static void main(String args[]) {
operation("5+2*5-6/2+1+5*12/3");
}
public static void operation(String m) {
ArrayList<Object> expressions = new ArrayList<Object>();
String e;
String x = "";
for (int i = 0; i < m.length(); i++) {
e = m.substring(i, i + 1);
if (!(e.equals("*") || e.equals("/") || e.equals("+") || e
.equals("-"))) {
x += e;
continue;
} else {
if (!x.equals("") && x.matches("[0-9]+")) {
int oper = Integer.parseInt(x);
expressions.add(oper);
expressions.add(m.charAt(i));
x = "";
}
}
}
if (!x.equals("") && x.matches("[0-9]+")) {
int oper = Integer.parseInt(x);
expressions.add(oper);
x = "";
}
for (int i = 0; i < expressions.size(); i++) {
System.out.println(expressions.get(i));
}
evaluateExpression(expressions);
}
public static void evaluateExpression(ArrayList<Object> exp) {
//Considering priorities we calculate * and / first and put them in a list mulDivList
ArrayList<Object> mulDivList=new ArrayList<Object>();
for (int i = 0; i < exp.size(); i++) {
if (exp.get(i) instanceof Character) {
if ((exp.get(i)).equals('*')) {
int tempRes = (int) exp.get(i - 1) * (int) exp.get(i + 1);
exp.set(i - 1, null);
exp.set(i, null);
exp.set(i + 1, tempRes);
}
else if ((exp.get(i)).equals('/')) {
int tempRes = (int) exp.get(i - 1) / (int) exp.get(i + 1);
exp.set(i - 1, null);
exp.set(i, null);
exp.set(i + 1, tempRes);
}
}
}
//Create new list with only + and - operations
for(int i=0;i<exp.size();i++)
{
if(exp.get(i)!=null)
mulDivList.add(exp.get(i));
}
//Calculate + and - .
for(int i=0;i<mulDivList.size();i++)
{
if ((mulDivList.get(i)).equals('+')) {
int tempRes = (int) mulDivList.get(i - 1) + (int) mulDivList.get(i + 1);
mulDivList.set(i - 1, null);
mulDivList.set(i, null);
mulDivList.set(i + 1, tempRes);
}
else if ((mulDivList.get(i)).equals('-')) {
int tempRes = (int) mulDivList.get(i - 1) - (int) mulDivList.get(i + 1);
mulDivList.set(i - 1, null);
mulDivList.set(i, null);
mulDivList.set(i + 1, tempRes);
}
}
System.out.println("Result is : " + mulDivList.get(mulDivList.size() - 1));
}
}

Stack overflow error in minimax algorim

Hi so I've recently started programming in java and I've set myself a task of making an AI for a tic tac toe game I've made
However the minmax algorithm is throwing a Stack Overflow error and I cant see in the error or the program where the problem is.
Here's the program:
public State minmax(boolean max, State currentState)
{
if (currentState.getNull() == 0) {
return currentState;
}
else {
State[] successorStates = currentState.getSuccessorStates(aiPlayer);
ArrayList<Integer> scoresTemp = new ArrayList<>();
for (State state : successorStates) {
scoresTemp.add(evaluate(aiPlayer, minmax(!max, state)));
}
Integer[] scores = (Integer[]) scoresTemp.toArray();
if (max) {
State maxState = successorStates[0];
int maxScore = evaluate(aiPlayer, maxState);
for (int score : scores) {
if (scores[0] > maxScore) {
maxScore = score;
maxState = successorStates[score];
}
}
return maxState;
}
else
{
State minState = successorStates[0];
int minScore = evaluate(aiPlayer, minState);
for (int score : scores) {
if (scores[0] > minScore) {
minScore = score;
}
}
return minState;
}
}
}
It returns the state which is the best move to make.
getNull() returns the amount of spaces left that can be played on.
getSuccesorStates(Player) returns all of the succeeding states of that state by making a new state of which contains the old moves and a new one of the Player.
evaluate() returns the value -1, 0 or 1 depending on a win, draw or loss in that state. None returns 0
edit:
public int getNull()
{
int amount = 0;
for (int x =0; x<9; x++)
{
if (getAllCells()[x]==null)
{
amount++;
}
}
return amount;
}
public State[] getSuccessorStates(Player player)
{
State[] states = new State[getNull()];
Player[][] stateCells = cells.clone();
int[][] nullPositions = getNulls();
for (int x=0; x<getNull(); x++)
{
stateCells[nullPositions[x][0]][nullPositions[x][1]] = player;
states[x] = new State(player, stateCells);
stateCells = cells.clone();
}
return states;
}
Caused by: java.lang.StackOverflowError
at sample.AI.minmax(AI.java:23)
at sample.AI.minmax(AI.java:32)
at sample.AI.minmax(AI.java:32)
.
.
.
23: if (currentState.getNull() == 0)
32: scoresTemp.add(evaluate(aiPlayer, minmax(!max, state)));
public Player[] getAllCells()
{
Player[] cellList = new Player[9];
for (int x = 0; x<3; x++)
{
for (int y = 0; y<3; y++)
{
cellList[y*3+x] = cells[x][y];
}
}
return cellList;
}
minmax is called in:
public Ply getPly(State state)
{
State bestState = minmax(true, state);
State[] successorStates = state.getSuccessorStates(aiPlayer);
ArrayList<State> states = new ArrayList<State>();
for (int x=0; x<successorStates.length; x++)
{
states.add(successorStates[x]);
}
int[][] nulls = state.getNulls();
Ply bestPly = new Ply(aiPlayer, nulls[states.indexOf(bestState)][0], nulls[states.indexOf(bestState)][1]);
return bestPly;
}
Thankyou if anyone could help:)
Your problem is here:
scoresTemp.add(evaluate(aiPlayer, minmax(!max, state)));
When you call the minmax method you create a bunch of data that uses up the memory ( java allows a certain amount of the computers memory to be used ).
You then inside minmax call minmax again making it create even more data and this is happening infinitely until there is no more memory left and Java throws the StackOverflow exception.

Java Locks synchronize methods baking transfer [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
Hello I have a Java application that takes an input number of operations to perform and it run different threads for each operation:
//create operations to execute
Thread t[] = new Thread [n_operations];
//we create a Bank with N accounts
Bank mybank = new Bank(N);
//execute a separate thread per operation
for (int i = 0; i < n_operations; i++) {
int id = i;
Operation o = new Operation(mybank, id);
t[i]= new Thread (o);
t[i].start();
}
for (int i=0;i<N;i++){
try{
t[i].join();
}catch(Exception e){;}
}
Now I need to perform concurrent transfer on the accounts, where the Bank class is defined like this:
public class Bank {
private static Account[] accounts;
final int MAX_balance = 100000;
int MAX_accounts = 0;
/* Create accounts of a bank */
public Bank (int N) {
accounts = new Account[N];
MAX_accounts = N;
for (int i = 0; i < N; i++)
accounts[i] = new Account (i, 1000);
}
public int getN(){
return MAX_accounts;
}
public synchronized int transfer(int from, int to, int amount) {
synchronized (accounts[from]){
synchronized (accounts[to]){
if (accounts[from].balance () < amount) {
try{
System.out.println("Error during transfer: Not enough Money");
}
catch(Exception err){
return 1;
}
}
accounts[from].sub(amount);
accounts[to].add(amount);
}
}
return 0;
}
}
When the program performs the operations:
public class Operation implements Runnable {
private Bank b;
int id;
Random r;
private final int MAX_TRANSFERENCIAS = 1000;
public Operation (Bank b, int id) {
this.b = b;
this.id = id;
}
public int syncronize(){
return 1;
}
public void run () {
r = new Random();
if(b == null)
throw new RuntimeException("b is null!");
if(r == null)
throw new RuntimeException("r is null!");
int max = b.getN();
//depend if there is a conflict or not
b.transfer (id,r.nextInt(max),r.nextInt(100));
}
}
I get a series of errors like this message:
at Bank.transfer(Bank.java:28) /* which is "synchronized (accounts[from]){" */
at Operation.run(Operation.java:33) /* which is "b.transfer
(id,r.nextInt(max),r.nextInt(100));" */
at java.lang.Thread.run(Unknown Source)
java.lang.ArrayIndexOutOfBoundsException: 4714
Do you think the Synchronization is ok?
Any suggestions? Many thanks
UPDATE (I can't answer myself)
There is a concept error in the main loop (for i..to n_operations),
the function is passing "int id = i;" as parameter for the source_account, while the n_operation number is bigger than the max value of the array, so the compiler reasonably says: ArrayIndexOutOfBoundsException.
As final contribution I would ask you to kindly check if the Synchronization is done correctly, as I am not an expert in multithreading. Many thanks again, and sorry for badly formulate the question this morning....
Edit:
Now that we know that the following line is the source of the NPE:
b.transfer (id,r.nextInt(max),r.nextInt(100));
So most likely b or r is null. You should put a break point there and debug into it to see if they are. You could also use assert or logging to display the values. Remember also that id or max could also cause a NPE if either is an Integer that is null and gets auto-boxed.
This wouldn't cause your NPE but be careful that n_operations may not be == 100? You are starting n_operations threads but joining with 100 of them:
for (int i=0;i<100;i++){
try {
t[i].join();
} catch(Exception e){;}
}
I always use the length of the array in these cases so you don't have a mismatch between what was allocated:
for (int i = 0; i < t.length; i++) {
Also, at the very least you should always log or print your exceptions. Catching and dropping exceptions often means you are hiding important debugging information.
} catch(Exception e){ e.printStackTrace(); }
One of the variables you are using in run() is null, but which one? Try adding the following to the beginning of Operation.run():
if(b == null)
throw new RuntimeException("b is null!");
if(r == null)
throw new RuntimeException("r is null!");
I presume that the lines you showed from run() include line 27. If not, please post the full source code for run().

Categories

Resources