How Should Null Pointer Exception Be Avoided In A Program
Aug 6, 2014
How should null pointer exception be avoided in a program. Should each and every place of access of a variable be checked for null and if null is there own customized exception should be thrown. Is this approach correct for avoiding null pointer exception.
View Replies
ADVERTISEMENT
Mar 23, 2015
I'm new to Java programming (taking a beginner's class) and our assignment is to program a game of Go Fish. I've got all my classes written (Card, CardPile, Player and GoFish). Now the problem is that I'm getting a NullPointerException when I run the GoFish class. The error seems to occur when I ask the program to check whether the player whose current turn it is, has a book (meaning 4 cards of the same value) in their hand. My idea was to run through the values 1 to 13, first checking to see if the value appeared in the player's hand:
if(players[currentTurn].hasCard(hasValue))
And if true, then remove all the cards matching the value from the player's hand, add to a new array of cards and then check to see if this array is of length 4 i.e. a book. If not, return the array of cards to the player's hand.
Here's the error message:
java.lang.NullPointerException
at CardPile.searchValue(CardPile.java:88)
at Player.hasCard(Player.java:15)
at GoFish.main(GoFish.java:98)
It references the following lines of code:
In GoFish.main:
// At the end of each turn, check to see if player currentTurn has made a book.
boolean hasBook = false;
int hasValue;
for (hasValue = 1; hasValue <= 13; hasValue++) {
// Runs through player's hand and removes all cards of the same value between 1 and 13 and places in a new array.
[Code] ....
I cannot figure out why I am getting the null pointer exception error!!!
View Replies
View Related
Aug 14, 2014
It is supposed to create an array of random strings and sort them according to their HTML numbers. It creates the array correctly and even compiles correctly, but has a null pointer exception when it comes to the sorting. (I have cut out other parts of the program that were irrelevant).
the lines that produces the null Pointer Exception is line 24. if(array[i].charAt(0)>array[maxIndex].charAt(0))...and 53.stringSelectionSort(stringArray);
import java.util.Arrays;
import java.util.Random;
/**tests the array.sort() subroutine vs. a
'selection sort' that I will write. a random list
of integers is used first and times are recorded to
determine which one is more efficient. A random list
of strings is also tested.**/
[code]....
View Replies
View Related
May 16, 2014
what i do keep getting nullpointerexception error whenever i input 1 or 2 whenever the code is asking me to input the type of display to be shown..
this is my error - "Exception in thread "main" java.lang.NullPointerException
at dakilangtaoako.DakilangTaoAko.alphabetSorter(Dakil angTaoAko.java:195)
at dakilangtaoako.DakilangTaoAko.main(DakilangTaoAko. java:91)
Java Result: 1 "
package dakilangtaoako;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.logging.Level;
import java.util.logging.Logger;
[code]....
View Replies
View Related
Aug 14, 2014
I've been closely following a tutorial series, and as far as I can tell my code is exactly the same, but not functioning.
The app throws a nullpointer exception here on "controller.saveToFile(fileChooser.getSelectedFile ());"
// Export data item
exportDataItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (fileChooser.showSaveDialog(MainFrame.this) == JFileChooser.APPROVE_OPTION) {
try {
controller.saveToFile(fileChooser.getSelectedFile());
[Code] ....
There are no errors popping up in the code, and I dont understand why there is a null pointer exception when Im saving this file.
View Replies
View Related
Oct 10, 2014
Take a look at this screenshot... my java integrated devlopment envirnment is telling me I have a null pointer on a line with three variables ALL which were initialized.
I thought a null pointer was called when a variable doesn't get initialized.
Edit: Here is the java file and resources being used: [URL]
View Replies
View Related
Apr 9, 2014
I am try to move circle.Below is my code...
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.Toolkit;
import java.awt.image.BufferStrategy;
import javax.swing.JFrame;
import javax.swing.JPanel;
[Code] .....
And I have error
run:
Exception in thread "main" java.lang.NullPointerException
at swingdesing.Game.buffer(Game.java:32)
at swingdesing.Game.moveBall(Game.java:27)
at swingdesing.Game.main(Game.java:51)
BUILD SUCCESSFUL (total time: 9 seconds)
how to overcome this?
View Replies
View Related
Oct 8, 2014
Should the piece of code below set prevent the comboBox from being used? All it does at the minute return a null pointer exception. See I am using the same window but I have an if statement so if a condition is true then it will change certain aspects of the window. I want it to be true if it equals export which is does and it's populated fine but when I try and hide it if the condition equals import it returns a null pointer?
comboBoxEnv.setEnabled(false);
View Replies
View Related
Jul 26, 2014
I get a null pointer error on line 17 of the following fragment. I suspect it has to do with the way I am reading the file, but I'm unsure. I can provide more information or code if necessary.
JFileChooser jfc = new JFileChooser();
jfc.setFileSelectionMode( JFileChooser.FILES_AND_DIRECTORIES );
int userInput = jfc.showOpenDialog( null );
if( userInput == JFileChooser.CANCEL_OPTION ){
[Code] .....
View Replies
View Related
Apr 16, 2014
I am getting a NullPointerException at my compareTo statement in this section of my code. Why this is popping up?
public static int findPos(String theArray[], String playerName, int arrayCount)
{
int index;
int pos;
for(index = 0; index < arrayCount; index++) {
while ((index < arrayCount) && (playerName.compareTo(theArray[index]) > 0)) {
index++;
}
}
pos = index;
return pos;
}
Error is also creeping up on the line highlighted in a comment as "THIS LINE", and is linked to the compareTo error above.
while(yesOrNo == 'Y' || yesOrNo == 'y')
{
switch(option)
{
//Add a Player and their Stats to the Array
[Code] ....
View Replies
View Related
Apr 2, 2014
i have a j sf application that is using web-services to communicate to another application and pass some parameters to it.The application has three methods one to call the webservice,another to insert some values into a database and the third method to call the two methods when i click a button in a form.The methods a are
update() this is for calling a webservice and passing parameters to it.
insertt() to in sert to a database.
all() to call the above two.
when i call upadate and insertt in all method am getting an error java lang null pointer exception but when i call just one of the methods it executes successfully.This is my code package softmint.com;
import java.sql.Connection;
//import java.sql.Date;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
//import java.text.SimpleDateFormat;
import javax.xml.ws.WebServiceRef;
[code]....
View Replies
View Related
Feb 17, 2014
My web application will load an applet with SWING components (Menu bar) on successful login to application.
Once page is loaded, i choose a menu item from the menu bar and click on it. Dynamic menu bar is loaded for the selected menu item. After that i am not able to perform any action on menu bar. Ending up with below error.
Note: My Application is absolutely working fine till JRE 1.7.17. But when i upgarde to higher version of JRE like 1.7.25 and above i am getting below error.
Exception in thread "AWT-EventQueue-4" java.lang.NullPointerException
at javax.swing.RepaintManager.scheduleProcessingRunna ble(Unknown Source)
at javax.swing.RepaintManager.addDirtyRegion0(Unknown Source)
at javax.swing.RepaintManager.addDirtyRegion(Unknown Source)
at javax.swing.JComponent.repaint(Unknown Source)
at java.awt.Component.repaint(Unknown Source)
[Code] ....
View Replies
View Related
Apr 12, 2015
I have an input text file as file.txt where, it consists of only real values separated with commas, and arranged as rows as columns as mentioned below :
1,2,3,4,5,6,10,5,8,9
1,4,7,8,9,0,6,4,3,2,1
2,4,5,8.1.3.4.6.7.9.0
the number of rows is 100 and the number of columns are 9, that is they are fixed.Above is just an example, the file consists of decimal values.What I require is for each column of values I need to find out it's average or mean, that is in above example,
for 1st column:(1+1+2)/3
for 2nd column(2+4+4)/3
for 3rd column(3+7+5)/3,,,,,,,like this till the last column.
So I need to take the input from the .txt file, calculate the column average of each column and the average of each column must be displayed as output. I have done a bit of coding, but it is giving a run-time error as NullPointerException.I will forward my code as attachment, the reading of file, is done as string in java and then it must be converted to double values, also to read the comma separated input from a file I have used the split().
View Replies
View Related
Sep 7, 2014
I'm getting constructor null pointer exception but i don't know what has gone wrong...
private int capacity; // maximum capacity of the board
private double minimum; // minimum distance of the flyer
private SortedLinkedList sortedList;
private int size = 0;
public ScoreBoard() {
capacity = 10;
minimum = 0.0;
sortedList = new SortedLinkedList();
[Code] ....
View Replies
View Related
Mar 31, 2015
I am trying to export data from a jtable to a pdf report but every time i try running the code it gives me this exception:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at GUI.QC_receiving_book.printButtonActionPerformed(QC_receiving_book.java:309)
at GUI.QC_receiving_book.access$600(QC_receiving_book.java:26)
at GUI.QC_receiving_book$7.actionPerformed(QC_receiving_book.java:165)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2018)
[Code] ....
I tried avoiding the null exception by using the if statement but it didn't work. The row I choose from the table is full meaning there are no empty attributes. and all the data are imported from a mysql database to the table as String so there can't be any casting errors.
This is the part of the source code with the problem and i will also post the printing method. I tried debugging the class and when stepping into the first if statement it opened the jTable.java file and pointed at the getSelectedRow() method and this sentence "variable information not available.source compiled without -g option"
private void printButtonActionPerformed(java.awt.event.ActionEvent evt) {
if(samplesTable.getSelectedRow() >= 0){
int row = samplesTable.getSelectedRow();
System.out.println(row);
for(int x=0;x<samplesTable.getColumnCount();x++){
String value = samplesTable.getModel().getValueAt(row, x).toString();
[Code] ....
View Replies
View Related
Jun 8, 2014
Question 1: I am working on an assignment where I have to remove an item from a String array (see code below). When I try to remove an item after entering it I get the following error "java.lang.NullPointerException." I am not sure how to correct this error.
Question 2: In addition, I am having trouble figuring out how to count the number of occurrences of each string in the array and print the counts. I've been looking at other posts but they are more advanced and I have not yet learned how to use some of the tools they are referring to.
private void removeFlower(String flowerPack[]) {
// TODO: Remove a flower that is specified by the user
Scanner input=new Scanner(System.in);
System.out.println();
System.out.println("Please enter the name of the flower you would like to remove:
[Code] ....
View Replies
View Related
Feb 7, 2014
i want to list files from resources folder like this:
@ManagedBean
public class galley implements Serializable {
private List<String> list;
@PostConstruct
public void init() {
list = new ArrayList<String>();
[Code] ....
but it give me a null pointer exception on fList .... The directory of resources is :
How is this caused and how can I solve it?
View Replies
View Related
Apr 26, 2015
This method keeps throwing a NullPointerException. Not only that, but its not doing what I want it to do.
Heres the code:
/*
Remove all the numbers from the queue and push onto the stack until an operator is reached
*/
private static void processQueue() {
// Check what is at the front of the queue. If an operator is found or the queue is empty, exit method.
while(queue.front() != null || !queue.front().equals("*") || !queue.front().equals("/") || !queue.front().equals("%")
|| !queue.front().equals("+") || !queue.front().equals("-"))
{
stack.push(queue.removeFront()); // push the operand onto the stack
}
}
Here is the method that calls the processQueue() method
/*
Process the mathematical expression using a stack and a queue
*/
private static double processExpression() {
// insert all elements from the stack to the queue for processing
while(stack.top() != null) {
queue.insertBack(stack.pop());
[Code] .....
View Replies
View Related
May 30, 2014
I am trying to program the A star algorithm using JButtons. Now I have some tweaking to do but I have to get past the errors first.
I am getting the following errors:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at AStar.findEndButton(AStar.java:40)
at Screen$1.actionPerformed(Screen.java:59)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2018)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2341)
[Code] ....
In my AStar class you will see these buttons which is an instance of matrixButtons
MatrixButtons[][] current;
MatrixButtons[][] endButton;
MatrixButtons[][] startButton;
MatrixButtons[][] nextCurrent;
MatrixButtons[][] temp;
MatrixButtons bestNextMove;
I really need them to handle several different methods. A full example of the full program is below.
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class Screen
[Code] ....
View Replies
View Related
Apr 16, 2014
I'm getting an error on line 137 and all it is rsmd = rs.getMetaData();The error happens only after I press a JButton and it is
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerExceptionat softwareDesign.createAccount.actionPerformed(createAccount.java:137)
There is a lot more to it but that has nothing to do with my code it's just the stuff with Eclipse anyway I want to know how do I fix this problem?
View Replies
View Related
Oct 15, 2014
So I'm trying to add two numbers using a stack class I made myself. I have a main class with a main method in which I use three stacks on holds one number one holds the other and then I sum one digit at a time keeping in midn that there may be a carry before putting the result on a third stack.
My problem is I'm getting a null pointer error when it should be putting an integer into the top of my stack which is index 0, I've checked my code and can't see why it would be doing this.This is my main method in my main class
import java.util.*;
import java.io.*;
public class CS25driver {
public static void main(String[]args) throws FileNotFoundException {
[code]...
my input file looks like a single line of input stating the problem followed by two lines of input which need to be summed.this is the error I'm getting
Exception in thread "main" java.lang.NullPointerException
at StackClass.push(StackClass.java:38)
at CS25driver.main(CS25driver.java:55)
View Replies
View Related
Dec 12, 2014
I am designing/coding a blackjack GUI program and I'm trying to add function to my JButtons. Problem is, I now have 2 NullPointerExceptions.
public class GameConsole {
Player user;
Player dealer;
Deck playingDeck;
ValidateInput validate = new ValidateInput();
[Code] .....
I am trying to do. I am getting the following exception/stack trace at line 14 in userTurn()
Exception in thread "main" java.lang.NullPointerException
at blackjackControls.GameConsole.userTurn(GameConsole.java:163)
at blackjackControls.GameConsole.gamePlay(GameConsole.java:87)
at blackjackControls.Main.main(Main.java:7)
and then the program continues and after I click the button I get :
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at blackjackControls.GameConsole.userTurn(GameConsole.java:163)
at blackjackControls.ResultPanel$1.actionPerformed(ResultPanel.java:34)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2028)
//and then about 30 more "at" lines
Why am I getting these exceptions and how do I fix it?
View Replies
View Related
Dec 12, 2014
This is what I wrote and I get this eror : Points to Ponder for Java Null Pointer Exceptions
public class Line{
private Punkt2d pStart;
private Punkt2d pEnde;
public Line(Punkt2d pStart, Punkt2d pEnde) {
this.pStart = pStart;
this.pEnde= pEnde;
[Code] ....
Erorr:
Exception in thread "main" java.lang.NullPointerException
at Line.getLength(Line.java:38)
at Aufgabe_6_1.main(Aufgabe_6_1.java:7)
View Replies
View Related
Mar 31, 2014
I'm using NetBeans to create this project and I have the gui registering text boxes, but it won't retrieve what the user entered, so the calculate button returns a null exception error.
Java Code:
package payroll;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.DecimalFormat;
import javax.swing.JButton;
import javax.swing.JComboBox;
[Code] .....
View Replies
View Related
May 25, 2014
I am currently making a double linked list class in my compsci class. i was absent for a few days and i need to make an add method for the class. when i go to compile test code i made i get a null pointer error on line 36. This is the node class i wrote and the double linked list class i wrote.
node class
public class Node{
// Two references and Data
Node prev;
Node next;
String data;
public Node(){
prev = null;
next = null;
[Code] ....
This is the class i need working with ( in the doublelinkedlist class)
public void add(Node n){
if(isEmpty()){
first = n;
return;
}
Node temp = first;
while(temp != null){
temp = temp.getNext();
}
temp.setNext(n);
temp.setPrev(temp);
}
View Replies
View Related
Aug 3, 2014
I am trying to build an expression tree program . I try to print it then I have java.nullpointer exception . Is it error in my code or what ?
I have 2 classes
one is BSTreeNode which is the nodes for the tree . It has
public class ExpressionTree {
public BSTreeNode root;
public BSTreeNode curr = root;
ExpressionTree() {
root = new BSTreeNode(null, null, null, null);
curr = root;
[Code] ....
My BSTreeNode
public class BSTreeNode {
BSTreeNode parent;
Object element; // Binary search tree element
BSTreeNode left; // Reference to the left child
BSTreeNode right; // Reference to the right child
// Constructor
BSTreeNode (Object elem)
[Code] ....
The error i am getting is
Exception in thread "main" java.lang.NullPointerException
at binaryexpressiontree.ExpressionTree.insert(ExpressionTree.java:38)
at binaryexpressiontree.test.main(test.java:22)
Java Result: 1
After implementing exception handler what i am getting is
java.lang.NullPointerException
root 1 *
root 2 1 error error error//these error print because of my catch clause
View Replies
View Related