this is my code - i have three classes and i will post all since i have no idea what i'm doing apparently

public class OneTwoTest

{

	public static void main(String[] args)

	{
		System.out.println("Welcome to One-Two Match!");
		Game g = new Game();
		g.play();
		System.out.println("Thank you for playing.");

	} // end main

} //end class
import java.util.Scanner;

public class Game

{

	public Player p1;   // human or computer player
	public Player p2;   // computer player
	int again;
	int sum;
	int a;
	int b;

	public Game()
	{
		p1 = new Player(a);
		p2 = new Player(b);
	}

	public void play()
	{

		sum = p1.declare() + p2.declare();
		if(sum%2==0)
		{	
			p2.deposit(sum);
			p1.withdraw(sum);
		}
		else
		{
			p1.withdraw(sum);
			p2.deposit(sum);
		}

		if(p1.score() > p2.score())
			System.out.println("Congratulations. Player 1 wins!");
		else
			System.out.println("Player 1 loses!");
	}

} // end of class
import java.util.Scanner;

public class Player
{

	private boolean isHuman;
	private int score=0;
	private Scanner input;
	

	public Player(int human)
	{
		System.out.println("If you would like to play, press 1. Otherwise, press 0 to have two computers play against each other.");
		human = input.nextInt();
		if (human>0)
			isHuman=true;
		else
			isHuman=false;

	}

	public int declare()
	{
		int theThrow;
	
		if(isHuman=true)
		{
			input = new Scanner(System.in);
			
			System.out.println("What would you like to throw? Enter either 1 or 2.");
			theThrow = input.nextInt();
			System.out.println("You threw a " + theThrow);
		}
		else
		{
			double t;

			t = (double) Math.random();
			theThrow = (int) (t+1.5);
			System.out.println("The computer threw a " + theThrow);
		}
		
		return theThrow;
	}
	

	public void deposit(int amount)
	{
		score = score + amount;
	}

	public void withdraw(int amount)
	{
		score = score - amount;
	}

	public int score()
	{
		return score;
	}
}

I get the following message

Welcome to One-Two Match!
If you would like to play, press 1. Otherwise, press 0 to have two computers play against each other.
Exception in thread "main" java.lang.NullPointerException
        at Player.<init>(Player.java:14)
        at Game.<init>(Game.java:16)
        at OneTwoTest.main(OneTwoTest.java:9)

Where is my mistake? I keep looking over it and can't find anything wrong. Please be explicit! Thank you

what is "input"?

I'm not sure if I know what you're asking me. As far as I know, it is used every time we want user input. So I used the scanner input.scanner bla bla whenever I needed a value from the user.

ok, your app if falling over @ player.java:14.

which is: human = input.nextInt();

at this point in your code, what does input represent?
note: there is a difference between declaring and initialising your variables / objects.

ok, your app if falling over @ player.java:14.

which is: human = input.nextInt();

at this point in your code, what does input represent?
note: there is a difference between declaring and initialising your variables / objects.

Well, input.nextInt() is asking for the user to enter a value right (I think)? So, the user enters a value, either 0 or 1, and this stores it into human. If human>0, meaning if it is 1, then isHuman is true, and an actual human will be playing the game against a computer. Otherwise, if the user enters 0, then two computers play against each other.

I don't know why it would go wrong here.

i am assuming the user doesn't even get to enter their value. am i wrong here? if so then input.nextInt() is not asking for any value...

do you know what the difference between declaring and initialising is? look at your declare() method, it should give you a clue as to what is happening...

You haven't initialized the input variable at the time that you are using it to get user input.

human = input.nextInt();

Initialize it to

input = new Scanner(System.in);

The thing is you need to declare variables, and then initialize them for use. If you do not initialize an object reference, then the value that it has is null , now when you use it to call a method then you get a NullPointerException since the object refers to null you cannot actually call a method on it.
If you check your code, in Player.java you do declare 'input' but do not initialize it before use.

You're right, the program crashes after it displays "Enter 1 if you would like to play..." and then the error message pops up. No I don't know the difference between declaring and initializing. I looked at my declare() method and I still haven't a clue.

I have been looking at this program for the past 10 hours now, playing with it every which way I can think of with no avail. I would appreciate some concrete hints over what to change since I am clueless as you might see. I appreciate your help, however the frustration has built up so much at this point that I have no idea what to do anymore. I would really appreciate it if you would just tell me what I'm doing wrong. I am very new to JAVA, only have been taking the class for the past 3 weeks.

You haven't initialized the input variable at the time that you are using it to get user input.

human = input.nextInt();

Initialize it to

input = new Scanner(System.in);

The thing is you need to declare variables, and then initialize them for use. If you do not initialize an object reference, then the value that it has is null , now when you use it to call a method then you get a NullPointerException since the object refers to null you cannot actually call a method on it.
If you check your code, in Player.java you do declare 'input' but do not initialize it before use.

OMG ok that solved it thank you so much. Although my program is not running the way I wanted it to, it still is running nonetheless so I thank you eternally. You just made my 10+ hours pay off.

the answer is posted by verruckt24, and he has a good explanation of what is going on. i couldn't just give you the answer straight up, had to make you work for it :)

the answer is posted by verruckt24, and he has a good explanation of what is going on. i couldn't just give you the answer straight up, had to make you work for it :)

I know but you know what, I noticed this, and I tried putting the code in the header, before my methods, and it didn't work. So I just assumed that that wasn't the problem. But I guess it was.

And, like I said, after 10 hours today, and 20+ in the past 3 days (yeah, I such that much), I'm fried.

@sillyboy : I too never give an answer straight up, as I believe you would learn a good deal trying such things then you ever would writing a correct program right away. But when I looked at his code I could see that he had initialized the input variable in other places, which made me believe that he missed it here, and I guess it's fine telling someone that "hey you missed this one here". So I gave him the statement with an exaplnation for the same to make clear that he understands the things and take enough pointers from it for further reading. Also when I told him about it, I didn't give him the exact place to put it in, I just told him to go over his code in the Player.java file and check where this statement should have been put, which he is supposed to know only if he had put the others in the place himself. I hope this clears up.

Also I think it's sometimes ok to drop a few hints to let the fellow make progress and make sure he is motivated for the further task. :)

@sillyboy : I too never give an answer straight up, as I believe you would learn a good deal trying such things then you ever would writing a correct program right away. But when I looked at his code I could see that he had initialized the input variable in other places, which made me believe that he missed it here, and I guess it's fine telling someone that "hey you missed this one here". So I gave him the statement with an exaplnation for the same to make clear that he understands the things and take enough pointers from it for further reading. Also when I told him about it, I didn't give him the exact place to put it in, I just told him to go over his code in the Player.java file and check where this statement should have been put, which he is supposed to know only if he had put the others in the place himself. I hope this clears up.

Also I think it's sometimes ok to drop a few hints to let the fellow make progress and make sure he is motivated for the further task. :)

Well, first - she ;) lol. I am a female who prior to this was considering majoring in CompSci but not anymore, which would explain the lack of females in the field, I suppose.

And yes, I just missed it, like I said I tried declaring input in the main method and after it gave me an error saying that it was unnecessary, I assumed something else was the problem. I never would have caught on if you hadn't helped me. So thank you guys, you truly are life savers.

Ohh I am so sorry miss, I should have figured it our from your username. But I guess answering the question took all my attention. ;)

And do take up the major, it's really so satisfying and fun, this programming thing.

@verruckt24, there is nothing to clear up. I didn't think you gave the answer away too easily or anything... I actually thought your post was good.

This is a code to solve a maze using A-star search algorithm. When I run it, it gives me the following error:

Exception in thread "main" java.lang.NullPointerException 

Can someone help me out?
Below is all the code:

import java.util.List;
import java.util.ArrayList;
import java.util.Queue;
import java.util.PriorityQueue;
import java.util.Stack;

public class MiFoMaze
{
    public static void main(String[] args)
    {
        AStar solution = new AStar(new Maze(new String[]
        {
              "S  X        X   X   "        
            , "XX XX XXXXX XXX X XX"        
            , "X  X    X X     X   "        
            , "XX   XX X XXX XXX X "        
            , "XXXX XX   X         "        
            , "     X    X       XX"        
            , " XXXXX X  XX XXXX   "        
            , " XX XX X  X     XX  "        
            , " XX XX X XXXXXX  XX "        
            , " X   X X  X     XX  "        
            , "   X   XX X X X  X  "        
            , "XXXXXXXX    X XXXX G"        
        }));
        solution.find();               
        System.out.println(solution); 
    }
}
class Maze      
{
    protected Tile[][] tile;
    protected Position SS;   
    protected Position GS;   
    public Maze(String[] mazeEntries)
    {
        tile = new Tile[mazeEntries.length][];
        for(int row=0; row<tile.length; row++)     
        {
            String Row = mazeEntries[row];
            tile[row] = new Tile[Row.length()];
            for(int column=0; column<tile.length; column++)  
            {
                tile[row][column] = new Tile(row, column, Row.charAt(column));
            }
            if(SS==null && Row.indexOf('S')>-1)
            {
                SS = new Position(row, Row.indexOf('S'));   
            }
            if(GS==null && Row.indexOf('G')>-1)
            {
                GS = new Position(row, Row.indexOf('G'));   
            }
        }
    }
    public Position[] getSteps(Position position)   
    {
        List<Position> steps = new ArrayList<Position>();
        if(isPassable(position.row-1, position.column))
        {
            steps.add(tile[position.row-1][position.column].finalPosition); 
        }
        if(isPassable(position.row+1, position.column))
        {
            steps.add(tile[position.row+1][position.column].finalPosition); 
        }
        if(isPassable(position.row, position.column-1))
        {
            steps.add(tile[position.row][position.column-1].finalPosition); 
        }
        if(isPassable(position.row, position.column+1))
        {
            steps.add(tile[position.row][position.column+1].finalPosition); 
        }
        return steps.toArray(new Position[]{}); 
    }
    private boolean isPassable(int row, int column)
    {
        return row>=0 && row<tile.length && column>=0 && column<tile[0].length && !tile[row][column].isWall; 
    }
}
class Tile
{
    final Position finalPosition;
    final boolean isWall;
    public Tile(int row, int column, char wall)
    {
        this.finalPosition = new Position(row, column); 
        this.isWall = (wall=='X');                      
    }
}
class Position
{
    final int row;
    final int column;
    public Position(int row, int column)   
    {
        this.row=row;
        this.column=column;
    }
    @Override
    @SuppressWarnings("EqualsWhichDoesntCheckParameterClass")
    public boolean equals(Object other)    
    {
        Position pos = (Position)other;
        return this.row==pos.row && this.column==pos.column;
    }
    @Override
    public int hashCode()       
    {
        return row*10000 + column;
    }
    @Override
        public String toString()
    {
        return "("+row+","+column+")";
    }
}
class Path implements Comparable<Path>
{
    protected Stack<Position> Spath;
    protected Position end;
    public Path(Position end)
    {
        this.Spath = new Stack<Position>();
        this.end = end;
    }
    public Path(Position start, Position end)
    {
        this(end);
        Spath.add(start);   
    }
    public Path(Path path, Position position, Position end)
    {
        this(end);
        Spath.addAll(path.Spath);   
        Spath.add(position);        
    }
    public int compareTo(Path other)
    {
        return probableCostOf(this.Spath)-probableCostOf(other.Spath);  
    }
    protected int probableCostOf(Stack<Position> Path)
    {
        return costSoFar(Path)+estimatedCostToExit(Path);   
    }
    protected int costSoFar(Stack<Position> Path)       
    {
       return Path.size();
    }
    protected int estimatedCostToExit(Stack<Position> Path) 
    {
        Position endPath = Path.peek();
        return Math.abs(endPath.row-end.row) + Math.abs(endPath.column-end.column);
    }
    public boolean contains(Position position)
    {
        return Spath.contains(position);
    }
    public Position peek()
    {
        return Spath.peek();
    }
    @Override
    public String toString()
    {
        return Spath.toString();
    }
}
class AStar
{
    final Maze finalMaze;
    private Queue<Path> Qpath;
    private Path shortestPath;
    public AStar(Maze maze)
    {
        this.finalMaze = maze;
        this.Qpath = new PriorityQueue<Path>();
        this.Qpath.add(new Path(maze.SS, maze.GS));
        this.shortestPath = null;
    }
    public boolean find()   
    {
        Position end = this.finalMaze.GS;   
        while(!this.Qpath.isEmpty())        
        {
            Path path = Qpath.poll();
            Position current = path.peek(); 
            for(Position next: finalMaze.getSteps(current))  
            {
                if(path.contains(next))                      
                {
                    continue;
                }
                Path newPath = new Path(path, next, end);    
                if(next.equals(end))                         
                {
                    shortestPath = newPath;
                    return true;
                }
                else
                {
                    Qpath.add(newPath);    
                }
            }
        }
        return false;       
    }
    @Override
    public String toString()
    {
        if(shortestPath==null)
        {
           return "MiFo couldn't find the path! :(";
        }
        return toString(shortestPath);  
    }
    public String toString(Path path)
    {
        StringBuilder result = new StringBuilder();
        for (Tile[] row : this.finalMaze.tile)
        {
            for (Tile tile: row)
            {
                if (this.finalMaze.SS.equals(tile.finalPosition))
                {
                    result.append('S'); 
                }
                else if (this.finalMaze.GS.equals(tile.finalPosition))
                {
                    result.append('G'); 
                }
                else if (path.contains(tile.finalPosition))
                {
                    result.append('O'); 
                }
                else
                {
                    result.append(tile.isWall ? 'X' : ' ');
                }
            }
            result.append('\n');
        }
        result.append("Total number of steps = ");   
        result.append(path.Spath.size());
        result.append('\n');
        return result.toString();
    }
}

Edited 3 Years Ago by mike_2000_17: Fixed formatting

To add to it, this is the output that i get when i run the program:

run:
Exception in thread "main" java.lang.NullPointerException
at Maze.isPassable(MiFoMaze.java:79)
at Maze.getSteps(MiFoMaze.java:71)
at AStar.find(MiFoMaze.java:189)
at MiFoMaze.main(MiFoMaze.java:26)
Java Result: 1
BUILD SUCCESSFUL (total time: 0 seconds)

import java.awt.*;  
import java.awt.event.*;    
import javax.swing.*;   
import java.util.*; 
import java.io.*;   
import java.text.*; 
import java.util.regex.*;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;

class Clustering1 
{
    public static void main(String[] args) throws IOException, FileNotFoundException
    {
        int diff_matrix[][] = new int[500][500];
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        System.out.println("Enter the data file name\n");
        String fname=br.readLine();       
        File file = new File(fname);
        if (file.exists())
            {
            FileReader fr = new FileReader(file);   
            LineNumberReader ln = new LineNumberReader(fr);

             int n = 0;

             while (ln.readLine() != null)  
             n++;
             ln.setLineNumber(1);
             for(int i=1;i<n-1;i++)
                {
                 for(int j=1;j<n-1;j++)
                    {
                     if(i!=j)
                         {


                                 ln.setLineNumber(i);
                                String line1=ln.readLine();
                                Pattern pat = Pattern.compile("[ ,]");
                                 ln.setLineNumber(j);
                                String line2=ln.readLine();

                                 String str1[]=pat.split(line1);
                                 String str2[]=pat.split(line2);
                                 int count=0;
                                 int s=0;
                                for(int p=0; p < str1.length; p++)
                         {
                                     if(str1[p].equals(str2[p]))
                                         count=count+1;
                         }
                         diff_matrix[i-1][j-1]=count;
                     }
                         else
                             diff_matrix[i-1][j-1]=0;
                     }
                    }
                    for(int i=0;i<n-2;i++)
                {
                        System.out.println();
                        for(int j=0;j<n-2;j++)
                    {
                            System.out.print(diff_matrix[i][j]+"\t");
                    }
                }     



        int neigh_matrix[][] = new int[500][500];
        int nm=0;
        int k=1;
        int min_matrix[]=new int[500];
        for(int i=0;i<n-1;i++)
                {           
            int min=diff_matrix[i][k];
            for(int j=0;j<n-1;j++)
                { 
            if(i!=j){
                    if(min>diff_matrix[i][j])
                        {
                        min=diff_matrix[i][j];
                            }
                        }
                    }
                    min_matrix[i]=min;
                    k=0;
                }
                for(int i=0;i<n-1;i++)
                {
                    neigh_matrix[i][nm]=i+1;
                    for(int j=0;j<n-1;j++)
                    {
                        if(min_matrix[i]==diff_matrix[i][j])
                        {
                            neigh_matrix[i][++nm]=j+1;

                        }
                    }
                }   
                for(int i=0;i<n-1;i++)
                {
                    System.out.println();
                    for(int j=0;j<neigh_matrix[i].length;j++)
                        System.out.println(neigh_matrix[i][j]+"\t");
                }

                int clusters[][] = new int[500][500];


        }
        else
        {
            System.out.println("File is not exist");
        }
    }
}

i am not getting correct output.. can u solve it

my error is:Exception in thread "main" java.lang.NullPointerException
        at java.util.regex.Matcher.getTextLength(Matcher.java:1127)
        at java.util.regex.Matcher.reset(Matcher.java:284)
        at java.util.regex.Matcher.<init>(Matcher.java:205)
        at java.util.regex.Pattern.matcher(Pattern.java:879)
        at java.util.regex.Pattern.split(Pattern.java:988)
        at java.util.regex.Pattern.split(Pattern.java:1050)
        at Clustering.main(Clustering.java:39)

Edited 3 Years Ago by mike_2000_17: Fixed formatting

This question has already been answered. Start a new discussion instead.