NullPointerException in processing with 2D array of objects - processing

I am creating a small game in processing and I am trying to print a 2D array of square objects. I have this NullPointerException and I cannot seem to find anything like it on the web.
int edge = 10;
public int sizeOfRect = 50;
public int numberOfRects = 10;
Rectangle[][] player = new Rectangle[numberOfRects][numberOfRects];
public int k;
public int l;
public int kcount=0;
public int lcount=0;
void setup(){
background(200);
size(565, 565);
}
void draw(){
for(k=edge; k<width-edge; k+=55){
for(l=edge; l<height-edge; l+=55){
player[kcount][lcount].display();
lcount++;
}
lcount=0;
kcount++;
}
kcount=0;
}
and the Rectangle Class
class Rectangle{
int i;
int j;
Rectangle(){
i=k;//xcoor
j=l;//ycoor
}
void display(){
fill(0);
rect(i,j,sizeOfRect,sizeOfRect);
}
}
And finally the exception
Plain.pde:17:0:17:0: NullPointerException Finished. Could not run the
sketch (Target VM failed to initialize). For more information, read
revisions.txt and Help? Troubleshooting. Could not run the sketch.
Thank you in advance

You're creating a 2D array, but you're never filling that array with any objects. In other words, your 2D array is full of null values. That's why you're getting a NullPointerException.
You need to fill your array with values. Here's an example:
player[1][2] = new Rectangle();
You probably want to use a nested for loop to fill your array.

Related

How can I create points, display them and store them in some sort of Array

I want to create points and then store them in an array. I'm doing this to put a linear regression through my data points afterwards. So I need to be able to cycle through all my points.
I could not find anything like that on the web for processing and as I was not really able to do it, I need your help. Here is my approach, but it doesn't seem to work:
ArrayList<dataPoint> dataPoints = new ArrayList<dataPoint>();
void setup(){
size(1000, 1000);
background(255);
}
void draw(){
for (int i = 1; i == dataPoints.size(); i++) {
// An ArrayList doesn't know what it is storing so we have to cast the object coming out
dataPoint Point = dataPoints.get(i);
Point.display();
}
}
void mousePressed() {
dataPoints.add(new dataPoint(mouseX, mouseY));
}
class dataPoint {
float x;
float y;
dataPoint(int tempX, int tempY) {
x = tempX;
y = tempY;
}
void display() {
strokeWeight(10);
stroke(255,0,0);
point(x,y);
}
}
I would like to have a program to create points and store them in an array (or something similar, that you can cycle through).
Most of your code makes sense, there are only two gotchas I could spot that may prevent you from cycling through all your points and visualising them:
your condition is will go to an array index out of bounds: try for (int i = 0; i < dataPoints.size(); i++)
remember to clear the frame, otherwise you're drawing on top of the same dots over and over again
Remember array indices start at 0 in Processing/Java (and likewise the last index will not be the size() of your array, but the 1 less, hence the < in the for condition)
Here is your code with the above tweaks:
ArrayList<dataPoint> dataPoints = new ArrayList<dataPoint>();
void setup(){
size(1000, 1000);
}
void draw(){
background(255);
for (int i = 0; i < dataPoints.size(); i++) {
// An ArrayList doesn't know what it is storing so we have to cast the object coming out
dataPoint Point = dataPoints.get(i);
Point.display();
}
}
void mousePressed() {
dataPoints.add(new dataPoint(mouseX, mouseY));
}
class dataPoint {
float x;
float y;
dataPoint(int tempX, int tempY) {
x = tempX;
y = tempY;
}
void display() {
strokeWeight(10);
stroke(255,0,0);
point(x,y);
}
}
Note that Processing has a handy PVector class (which has x,y properties) so you could do something like this:
ArrayList<PVector> dataPoints = new ArrayList<PVector>();
void setup(){
size(1000, 1000);
strokeWeight(10);
stroke(255,0,0);
noFill();
}
void draw(){
background(255);
beginShape();
for (int i = 0; i < dataPoints.size(); i++) {
PVector point = dataPoints.get(i);
vertex(point.x,point.y);
}
endShape();
}
void mousePressed() {
dataPoints.add(new PVector(mouseX, mouseY));
}
This a bit of a detail, but I recommend to following Java Naming Convention to keep the code consistent. (For example: renaming the dataPoint class to DataPoint and renaming the Point instance to point)

Null Pointer exception in Processing in Array. Tried everything

I am making a 2d side scrolling game and I'm stuck. Im writing the class for the objects which will spawn increasingly and which the Player has to avoid. But sadly I am getting a Nullpointerexception and I cannot figure out why.Before I cleaned up the code in the main and transformed it to a class, the whole thing was working. I think I'm initializing the Array correctly and no variables are left undefined. I've only been using processing for the past months so I might have overseen something.
Thanks a lot for your help
public class Blockfield {
private int Blockcount;
private PImage Blockpic;
private Block block[];
//Constructor
public Blockfield (int Blockcount) {
this.Blockcount = Blockcount;
//new array
block = new Block [Blockcount];
for ( int i=0; i < Blockcount; i++) {
block[i] = new Block( width+Blockpic.width, random (height));
}
}
//Draw method for this class
public void draw () {
for (int i =frameCount/100; i >0; i--) {
image ( Blockpic, block[i].x, block[i].y);
//moves blocks right to left
block[i].x -=7 ;
//spawns block when they leave the screen
if (block[i].x < 0) {
block[i] = new Block( width+Blockpic.width, random (height));
}
}
}
}
class Block {
float x, y;
Block ( float x, float y) {
this.x= x;
this.y= y;
}
}
Main:
Blockfield blockfield;
PImage Blockpic;
void setup () {
size (1291, 900);
blockfield = new Blockfield(100);
Blockpic = loadImage("block2.png");
}
void draw () {
background ( 10);
}
The problem was that I was trying access Blockpic.width in your Blockfield constructor before Blockpic had been assigned. The solution was to load the Image within the constructor of the class.
Working code:
public class Blockfield {
private int Blockcount;
private PImage Blockpic;
private Block block[];
//Constructor
public Blockfield (int Blockcount) {
this.Blockcount = Blockcount;
Blockpic = loadImage("block2.png");
//new array
block = new Block [Blockcount];
for ( int i=0; i < Blockcount; i++) {
block[i] = new Block( width+Blockpic.width, random (height));
}
}
//Draw method for this class
public void draw () {
for (int i =frameCount/100; i >0; i--) {
image ( Blockpic, block[i].x, block[i].y);
//moves blocks right to left
block[i].x -=7 ;
//spawns block when they leave the screen
if (block[i].x < 0) {
block[i] = new Block( width+Blockpic.width, random (height));
}
}
}
}
class Block {
float x, y;
Block ( float x, float y) {
this.x= x;
this.y= y;
}
}
Thanks to everyone for the help!!!

Dynamical drawing images in Cinder (Windows)

I have used Cinder about few weeks and i have some problem.
I am using method "drag-and-drop" in my program :
void TutorialApp::fileDrop(FileDropEvent drop){ /// drop are images
for(size_t i=0; i<drop.getNumFiles();++i){
Vertex imageVertex = Vertex((Vec2i(drop.getPos().x, drop.getPos().y+200)));
imageVertex.path = drop.getFiles()[i];
and next my step is draw Vertex with associeted image. So that is question: how to add resources in this case, or maybe there is more easy solution? Thank
Straight to the point:
First of all,you want to keep images (i.e gl::Texture) in your objects, that you want to draw. So in your class Vertex, add this gl::Texture as member. And then I suggest to use this function to load image and edit constructor, to take gl::Texture as parameter.
So you end up with something like this:
class testVertex
{
public:
testVertex(Vec2i _pos, gl::Texture image);
void draw(){
gl::draw(texture, pos);
}
private:
gl::Texture texture;
Vec2i pos;
};
///constructor
testVertex::testVertex(Vec2i _pos, gl::Texture image)
{
pos = _pos;
texture = image;
}
class BasicApp : public AppNative {
public:
void setup();
void mouseMove( MouseEvent event );
void mouseUp( MouseEvent event );
void keyUp(KeyEvent event);
void fileDrop(FileDropEvent event);
void update();
void draw();
//// create container for testVertex
vector <testVertex> mVertices;
}
/// To load images via drop...
void BasicApp::fileDrop(FileDropEvent event){
gl::Texture fileTexture = loadImage(event.getFile(0));
mVertices.push_back(testVertex(Vec2i(event.getX(), event.getY()), fileTexture));
}
/// To draw images...
void BasicApp::draw(){
for (int i = 0; i < mVertices.size(); i++)
{
mVertices[i].draw();
}
}
///

A more effective algorithm

This is my first time posting question, do pardon me if anything I do is wrong.
My question here is how to get a faster algorithm from this code? i'm currently using 2 stacks to implement the code such that it will get the minimum value out of the range of index User asks for input.
Example (2,3,4,5,1), if (user selects (1,4)), it means they are looking at (2,3,4,5), which the output is 2.
Thanks.
import java.util.*;
interface StackADT <Integer> {
// check whether stack is empty
public boolean empty();
// retrieve topmost item on stack
public int peek() throws EmptyStackException;
// remove and return topmost item on stack
public int pop() throws EmptyStackException;
// insert item onto stack
public void push(int item);
}
class StackArr <Integer> implements StackADT <Integer> {
private int[] arr;
private int top;
private int maxSize;
private final int INITSIZE = 1000;
public StackArr() {
arr = (int[]) new int[INITSIZE]; // creating array of type E
top = -1; // empty stack - thus, top is not on an valid array element
maxSize = INITSIZE;
}
public boolean empty() {
return (top < 0);
}
public int peek() throws EmptyStackException {
if (!empty()) return arr[top];
else throw new EmptyStackException();
}
public int pop() throws EmptyStackException {
int obj = peek();
top--;
return obj;
}
public void push(int obj) {
if (top >= maxSize - 1) enlargeArr();
top++;
arr[top] = obj;
}
}
class RMQ{
//declare stack object
Stack<Integer> stack1;
public RMQ(){
stack1 = new Stack<Integer>();
}
public void insertInt(int num){
stack1.push(num);
}
public int findIndex(int c, int d){
Stack<Integer> tempStack = new Stack<Integer>();
Stack<Integer> popStack = new Stack<Integer>();
tempStack = (Stack)stack1.clone();
while (d != tempStack.size())
{
tempStack.pop();
}
int minValue = tempStack.pop();
popStack.push(minValue);
while (c <= tempStack.size())
{
int tempValue = tempStack.pop();
if(tempValue >= minValue)
{
continue;
}
else
{
popStack.push(tempValue);
minValue = tempValue;
}
}
return popStack.pop();
}
}
public class Pseudo{
public static void main(String[] args){
//declare variables
int inputNum;
int numOfOperations;
//create object
RMQ rmq = new RMQ();
Scanner sc = new Scanner(System.in);
//read input
inputNum = sc.nextInt();
//add integers into stack
for(int i=0; i < inputNum; i++){
rmq.insertInt(sc.nextInt());
}
// read input for number of queries
numOfOperations = sc.nextInt();
// Output queries
for(int k=0; k < numOfOperations; k++){
int output = rmq.findIndex(sc.nextInt(), sc.nextInt());
System.out.println(output);
}
}
}
Why are you using a stack? Simply use an array:
int[] myArray = new int[inputNum];
// fill the array...
// get the minimum between "from" and "to"
int minimum = Integer.MAX_VALUE;
for(int i = from ; i <= to ; ++i) {
minimum = Math.min(minimum, myArray[i])
}
And that's it!
The way I understand your question is that you want to do some preprocessing on a fixed array that then makes your find min operation of a range of elements very fast.
This answer describes an approach that does O(nlogn) preprocessing work, followed by O(1) work for each query.
Preprocessing O(nlogn)
The idea is to prepare a 2d array SMALL[a,k] where SMALL[a,k] is the minimum of the 2^k elements starting at a
You can compute this array in a recursive way by starting at k==0 and then building up the value for each higher element by combining two previous elements together.
SMALL[a,k] = min(SMALL[a,k-1] , SMALL[a+2^(k-1),k-1])
Lookup O(1) per query
You are then able to instantly find the min for any range by combining 2 preprepared answers.
Suppose you want to find the min for elements from 100 to 133. You already know the min of 32 elements 100 to 131 (in BIG[100,5]) and also the min of 32 elements from 102 to 133 (in BIG[102,5]) so you can find the smallest of these to get the answer.
This is Range Minimum Query problem.
There are some algorthms and data structures to solve it effectively

Load multiple images in Processing

I would like to load and draw multiple/all images from a directory in Processing.
I cant find a way to extend the one image example:
PImage a;
void setup() {
size(800,800);
background(127);
a = loadImage("a/1.jpg");
noLoop();
}
void draw(){
image(a,random(300),random(300),a.width/2, a.height/2);
}
to multiple images.
Is there a simple way to achieve this?
Thank you very much.
I'm sure there are more elegant ways to do it, but wouldn't something as simple as this work?
PImage a;
Pimage b;
void setup() {
size(800,800);
background(127);
a = loadImage("a/1.jpg");
b = loadImage("b/1.jpg");
noLoop();
}
void draw(){
image(a,random(300),random(300),a.width/2, a.height/2);
image(b,random(300),random(300),b.width/2, b.height/2);
}
You can find an example of listing a directories here: http://processing.org/learning/topics/directorylist.html. The reference section for loops is here: http://processing.org/reference/loop_.html.
Imagine u have a known number of images (n) called 0.jpg, 1.jpg, 2.jpg..., then u can do sth like this:
PImage[] fragment;
int n=3;
void setup() {
size(400, 400);
fragment=new PImage[n];
for(int i=0;i<fragment.length;i++){
fragment[i]=loadImage(str(i) + ".jpg");
}
}
void draw(){
for(int i=0;i<fragment.length;i++){
image(fragment[i],20*i,20*i);
}
}

Resources