Jump to content

Learning Java - If Statement Error

I'm trying to learn Java and I'm creating a game where text falls from the top of the screen to the bottom and you need to type the word before it reaches the bottom to win. Right now I'm trying to set it up so when a word falls to the bottom of the screen, it is deleted and another instance is created. However, it doesn't work and I am given this error:

 

Exception in thread "Thread-2" java.lang.NullPointerException
    at Game.tick(Game.java:83)
    at Game.run(Game.java:64)
    at java.lang.Thread.run(Unknown Source)

 

Can anyone help? :/

 

Game Class

 

import java.awt.Canvas;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.image.BufferStrategy;
import java.awt.image.BufferedImage;

import javax.swing.JFrame;

public class Game extends Canvas implements Runnable{
    private static final long serialVersionUID = 1L;
    public static final int WIDTH = 640;
    public static final int HEIGHT = 480;
    public final String TITLE = "Advanced Higher Computing Project";
    
    private boolean running = false;
    private Thread thread;
    
    private BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
    
    private Controller c;
    private Word w;
        
    private void init(){
        c = new Controller(this);
    }
    
    private synchronized void start(){
        if(running)
            return;
        running = true;
        thread = new Thread(this);
        thread.start();
    }
    
    private synchronized void stop(){
        if(!running)
            return;
        
        running = false;
        try {
            thread.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.exit(1);
    }
    
    
    public void run(){
        init();
        long lastTime = System.nanoTime();
        final double amountOfTicks = 60.0;
        double ns = 1000000000 / amountOfTicks;
        double delta = 0;
        int updates = 0;
        int frames = 0;
        long timer = System.currentTimeMillis();
        while(running){
            long now = System.nanoTime();
            delta += (now - lastTime) / ns;
            lastTime = now;
            if (delta >= 1){
                tick();
                updates++;
                delta--;
            }
            render();
            frames++;
            
            if(System.currentTimeMillis() - timer > 1000){
                timer +=1000;
                System.out.println(updates + " Ticks, FPS " + frames);
                updates = 0;
                frames = 0;
            }
            
        }
        stop();
    }
    
        private void tick(){
            if(w.getDead() == true) {
                c.addWord(new Word(200, 20, this));
            }
            c.tick();
    }

    
    private void render(){
        BufferStrategy bs = this.getBufferStrategy();
        if(bs == null){
            createBufferStrategy(2);
            return;
        }
        Graphics g = bs.getDrawGraphics();
        ////
        c.render(g);
        g.setColor(Color.white);
        g.fillRect(0,0,getWidth(),getHeight());
        g.setColor(Color.red);
        g.fillRect(0,400,getWidth(),20);
        c.render(g);

        ////
        g.dispose();
        bs.show();
    }
    public static void main(String args[]){
        Game game = new Game();
        
        game.setPreferredSize(new Dimension(WIDTH, HEIGHT));
        game.setMaximumSize(new Dimension(WIDTH, HEIGHT));
        game.setMinimumSize(new Dimension(WIDTH, HEIGHT));

        
        JFrame frame = new JFrame(game.TITLE);
        
        frame.add(game);
        frame.pack();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setResizable(false);;
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
        
        game.start();
    }
}

 

 

Word Class

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;

public class Word {

    private double x;
    private double y;
    private boolean dead;
    
    public Word(double x, double y, Game game){
        this.x = x;
        this.y = y;
        this.dead = false;
    }
    
    public void tick(){
        y+=3;
        if(y >= 400)
            dead = true;
    }
    

    public void render(Graphics g){
        //set up text style
        Font font = new Font("Serif", Font.BOLD, 36);
        g.setFont(font);
        g.setColor(Color.black);
        g.drawString("Hello", (int)x, (int)y);
        
    }

    public boolean getDead() {
        return dead;
    }

    
    public double getY(){
        return y;
    }
    
}
 

Controller Class

import java.awt.Graphics;
import java.util.LinkedList;

public class Controller {

    private LinkedList<Word> w = new LinkedList<Word>();
    
    Word TempWord;
    Game game;
    
    public Controller(Game game){
        this.game = game;
    }
    
    public void tick(){
        for(int i = 0; i < w.size(); i++){
            TempWord = w.get(i);
            if(TempWord.getY() >= 400)
                removeWord(TempWord);
            TempWord.tick();

        }
    }
    
    public void render(Graphics g){
        for(int i = 0; i < w.size(); i++){
            TempWord = w.get(i);
            
            TempWord.render(g);
        }
    }
    
    public void addWord(Word block){
        w.add(block);
    }
    
    public void removeWord(Word block){
        w.remove(block);
    
    }
    
}
 

Cheers & Best Regards,

Arcapse

Link to comment
https://linustechtips.com/topic/716315-learning-java-if-statement-error/
Share on other sites

Link to post
Share on other sites

I am not too advanced in Java programming, and I might be stating the obvious, but your dead variable is given a null value at some point, and the bolded methods try to access the null value leading to a null pointer. Maybe look over all parts of the code that involve the dead variable and make sure it is never null. And if you only declare an object variable without assigning values to it, it will be null. 

Link to post
Share on other sites

Looks like your controller class 'c' 'w' is never initialized, you get that error trying to call a function on a null object.

 

Edit:

After looking at it a bit more closely, it seems you never run your run() method which contains your init() method so your controller object 'c' is never created. 

 

Edit 2: never mind

Link to post
Share on other sites

35 minutes ago, NoGravityPanda said:

Try removing the "==true", it isnt needed and probably whats causing the problem, in java to compare booleans you use one =

No! That sets the value don't do that! Just put the value directly inside the if statement to compare values. Although == works, it's a bit less concise and if you have a typo, you might end up with a single '=' which is bad.

 

public class test {

	public static void main(String[] args) {
		boolean t = true;
		boolean f =  false;
		
		if(f=t){
			System.out.println("Whoops");
		}
		if(f==false){ //this is never printed out because you changed the value in the last if statement
			System.out.println("That's better");
		}
		if(f== true){
			System.out.println("I screwed up");
		}
		if(t){
			System.out.println("This is the best");
		}

	}

}
/**
Output:

Whoops
I screwed up
This is the best
**/

 

Link to post
Share on other sites

1 hour ago, luckydog32 said:

No! That sets the value don't do that! Just put the value directly inside the if statement to compare values. Although == works, it's a bit less concise and if you have a typo, you might end up with a single '=' which is bad.

 


public class test {

	public static void main(String[] args) {
		boolean t = true;
		boolean f =  false;
		
		if(f=t){
			System.out.println("Whoops");
		}
		if(f==false){ //this is never printed out because you changed the value in the last if statement
			System.out.println("That's better");
		}
		if(f== true){
			System.out.println("I screwed up");
		}
		if(t){
			System.out.println("This is the best");
		}

	}

}
/**
Output:

Whoops
I screwed up
This is the best
**/

 

Whoops, I screwed up.

Sorry, after a very confusing and pretty stupid teacher I somehow forgot things

Link to post
Share on other sites

22 hours ago, luckydog32 said:

Looks like your controller class 'c' is never initialized, you get that error trying to call a function on a null object.

 

Edit:

After looking at it a bit more closely, it seems you never run your run() method which contains your init() method so your controller object 'c' is never created. 

This is incorrect. The run method is invoked at the start of a new thread (Game.start() creates a new thread based off itself, and then starts the thread, which invokes the Game.run() method which calls the Game.init() method).

 

22 hours ago, fizzlesticks said:

You never initialize "w".

I also believe this is the issue. 

15" MBP TB

AMD 5800X | Gigabyte Aorus Master | EVGA 2060 KO Ultra | Define 7 || Blade Server: Intel 3570k | GD65 | Corsair C70 | 13TB

Link to post
Share on other sites

On 2.1.2017 at 7:22 PM, NoGravityPanda said:

Try removing the "==true", it isnt needed and probably whats causing the problem, in java to compare booleans you use one =

Never compare values with one =, it will set the value of the variable to true. You can however completly remove the == true as an if statement is always looking for a boolean value. You get that by f.e. comparing integers (if(x == 20)) or strings (if(str == "something")) but a boolean value already is a boolean value. 

My Rig: AMD Ryzen 5800x3D | Scythe Fuma 2 | RX6600XT Red Devil | B550M Steel Legend | Fury Renegade 32GB 3600MTs | 980 Pro Gen4 - RAID0 - Kingston A400 480GB x2 RAID1 - Seagate Barracuda 1TB x2 | Fractal Design Integra M 650W | InWin 103 | Mic. - SM57 | Headphones - Sony MDR-1A | Keyboard - Roccat Vulcan 100 AIMO | Mouse - Steelseries Rival 310 | Monitor - Dell S3422DWG

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×