GIDForums  

Go Back   GIDForums > Computer Programming Forums > Java Forum
User Name
Password
Register FAQ Members List Calendar Search Today's Posts Mark Forums Read

 
 
Thread Tools Search this Thread Rate Thread
  #1  
Old 10-Jul-2009, 08:40
flar3star flar3star is offline
New Member
 
Join Date: Jul 2009
Posts: 3
flar3star is on a distinguished road

Exception in thread "main" java.lang.NullPointerException


JAVA Code:
 import java.util.Scanner;
 
public class Assignment1 {
    
    public static void main(String[] args) {
    	
    	Scanner input = new Scanner(System.in);
    	
    	Item[] items = new Item[100];
    	
    	int i = 0;//Used in for-loop counts
    	int j = 0;//Used in for-loop counts
    	int entries = 0;//Record entries of records
    	int first = 0;//Check is the first record to be entered
    	boolean duplicate = true;//Check for duplication of record
    	boolean result = true;//Track seaching
    	
    	int optionMenu = 0;//Used for menu
    	String optionContinue;//Used for continue option
    	
    	//do-while loop for user to prompt back to main menu(optionMenu)
    	do{
    		Print.option();//print menu
    		optionMenu = input.nextInt();
    		
    		//Add New Record
    		if(optionMenu == 1) {
    			System.out.println("\nAdd New Record");
    			System.out.print("No. of Entries : ");//Record number of entries at a time
    			int looping = input.nextInt();
    			
    			System.out.println();
    			Print.sample();//Sample to guide users
    			
    			//Number of entries's for-looping
    			for(i = 0; i < looping; ++i) {
       				System.out.print("Enter item Number         : ");
       				input.useDelimiter("\n");
       				String itemNumber = input.next();
       				
       				System.out.print("Enter item description      : ");
       				input.useDelimiter("\n");
       				String itemDesc = input.next();
       					
       				System.out.print("Enter selling price : ");
       				double sellPrice = input.nextDouble();

       				System.out.print("Enter quantity on hand        : ");
       				int quantity = input.nextInt();
       				
       				System.out.println("===========================================================");
					
					
					
					//If first time key in date run statement
       				if(first == 0){
       					++first;//Track if is the first record key in
       					items[i] = new Item(itemNumber, itemDesc, sellPrice, quantity);
       				}
       				//Else continue key in record		
       				else{
       					entries = items[0].getEntries();//Get number of entries entered
       					for(j=0; j<entries; ++j){
       						
       						duplicate = items[j].equals(itemNumber, itemDesc, sellPrice, quantity);//Check for duplication of entries
       						
       						if(duplicate == true) {
       							Print.duplicateError();
       							--i;
       							--looping;
       							break;
       						}
       					}
       					if(duplicate == false)//else save record
       						items[entries] = new Item(itemNumber, itemDesc, sellPrice, quantity);
       				}	
    			}
    		}
    		
    		//Generate List of Record Entered
    		else if(optionMenu == 2) {
    			System.out.println("Generate List of Record Entered");
    			entries = items[0].getEntries();//Get number of record entered
    			
    			for(i=0; i<entries; ++i) {
    				System.out.println(i+1 + ". " + items[i].getItemNumber());
    			}

    			System.out.print("\nPerson no : ");
    			int searchItem = input.nextInt();
    			searchItem = searchItem - 1;
    			//Print record searched
    			System.out.println("item number     : " +items[searchItem].getItemNumber());
    			System.out.println("item description  : " +items[searchItem].getItemDesc());
    			System.out.println("selling price: " +items[searchItem].getSellPrice());
    			System.out.println("quantity on hand    : " +items[searchItem].getQuantity());
    		}
    		
    		//Search Record by Name
    		else if(optionMenu == 3) {
    			System.out.println("Search Record by Name");
    			System.out.print("Number : ");
    			input.useDelimiter("\n");
    			String searchNumber = input.next();
    			
    			entries = items[0].getEntries();//Get entries of record entered
    			
    			for(i=0; i<entries; ++i) {
    				
    				boolean booleanName = items[i].searchNumber(searchNumber);//Search record
    				
    				if(booleanName == true) {//Print if record found
    					System.out.println("\nRecord no. " + (i+1));
    					System.out.println("item number     : " + items[i].getItemNumber());
    					System.out.println("item description  : " + items[i].getItemDesc());
    					System.out.println("selling price: " + items[i].getSellPrice());
    					System.out.println("quantity on hand    : " + items[i].getQuantity());
    					
    					result = true;//Track if the record is found or not
    				}
    				else
    					result = false;//Track if the record is found or not
    			}
    			
    			if(result == false)//Print if record not found
    			System.out.println("Record not found.");
    		}
    		
    		//Modifiy Record
    		else if(optionMenu == 4) {
    			System.out.print("Entry No. : ");
    			int searchEntry = input.nextInt();
    			
    			System.out.print("\n\nEnter item number      : ");
       			input.useDelimiter("\n");
       			String itemNumber = input.next();
       				
       			System.out.print("Enter item description      : ");
       			input.useDelimiter("\n");
       			String itemDesc = input.next();
       					
       			System.out.print("Enter selling price : ");
       			double sellPrice = input.nextDouble();
       			
       			System.out.print("Enter quantity on hand        : ");
       			int quantity = input.nextInt();
       			
       			entries = items[0].getEntries();//Retrieve record entered
       			//Check for duplication
       			for(i = 0; i<entries; ++i) {
       				duplicate = items[i].equals(itemNumber, itemDesc, sellPrice, quantity);
       			}
       			
       			if(duplicate == true)//print if duplicated record are found
       				Print.duplicateError();
       					
       			else//Save if it not a duplicated record
       				items[searchEntry-1].makeCopy(itemNumber, itemDesc, sellPrice, quantity);
    		}
    		//Exit program 
    		else if(optionMenu == 5)
    			break;
    		//Check for continue looping
    		System.out.print("Do you want to continue (Y/N)?");
			optionContinue = input.next();
			
			System.out.println();
    	}while(optionContinue.equals("N") == false && optionContinue.equals("n") == false);
    	
    	Print.createBy();
    }
    
}





Quote:
Enter item Number : 2222
Enter item description : dssd
Enter selling price : 2
Enter quantity on hand : 2
================================================== =========
Enter item Number : 566555
Enter item description : dsdsdf
Enter selling price : 5
Enter quantity on hand : 4
================================================== =========
Do you want to continue (Y/N)?y

1. Add new Item
2. Generate List of Record Entered
3. Search Record by Item Number
4. Modifiy Record
5. Updated Quantity on Hand
6. Exit

Enter your choice : 2
Generate List of Record Entered

Person no : 2
Exception in thread "main" java.lang.NullPointerException
at Assignment1.main(Assignment1.java:94)

Process completed.

could any kind ones please tell me where have i made my mistakes? im quite pissed and sad i just cant figure it out , haih.
Last edited by LuciWiz : 10-Jul-2009 at 08:51. Reason: Please insert your Java code between [java] & [/java] tags
  #2  
Old 10-Jul-2009, 09:27
fakepoo fakepoo is offline
Regular Member
 
Join Date: Oct 2007
Posts: 713
fakepoo is a jewel in the roughfakepoo is a jewel in the roughfakepoo is a jewel in the rough

Re: Exception in thread "main" java.lang.NullPointerException


Your problem is here:

JAVA Code:
//If first time key in date run statement
       				if(first == 0){
       					++first;//Track if is the first record key in
       					items[i] = new Item(itemNumber, itemDesc, sellPrice, quantity);
       				}
Because when you enter your second item, the value of first is not zero and you never create a new Item(). Then, when you try to access items[1], it is still null, hence the null reference exception.
  #3  
Old 10-Jul-2009, 09:44
Kimmo Kimmo is offline
Member
 
Join Date: Mar 2007
Location: Finland
Posts: 285
Kimmo is a jewel in the roughKimmo is a jewel in the roughKimmo is a jewel in the rough

Re: Exception in thread "main" java.lang.NullPointerException


You're not giving us the whole code (classes Item and Print are missing) so we cannot test run it outselves. You're not giving us the whole sample run, so I guess one can only assume that you've chosen the first option in the menu before your sample run begins.

Generally this exception occurs when you're trying to access a non-initialized object. So it would seem that for one reason or another items[searchItem] is not initialized (since you input '2' on your test run and then subtract one, it's index 1).

So it seems one must go looking to the 'choice 1' portion of the program. Here is, in my opinion, the most interesting part:
JAVA Code:
//If first time key in date run statement
                if(first == 0){
                    ++first;//Track if is the first record key in
                    items[i] = new Item(itemNumber, itemDesc, sellPrice, quantity);
                }
                //Else continue key in record
                else{
                    entries = items[0].getEntries();//Get number of entries entered
                    for(j=0; j<entries; ++j){

                        duplicate = items[j].equals(itemNumber, itemDesc, sellPrice, quantity);//Check for duplication of entries

                        if(duplicate == true) {
                            Print.duplicateError();
                            --i;
                            --looping;
                            break;
                        }
                    }
                    if(duplicate == false)//else save record
                        items[entries] = new Item(itemNumber, itemDesc, sellPrice, quantity);
                }
If first is 0, then you enter the record at index 'i'. Which is probably 0 too since it's the first run through the loop, so that should be in order. But what happens for the consecutive records?

If first is not 0, you do this:
JAVA Code:
                    entries = items[0].getEntries();//Get number of entries entered
What does Item::getEntries() return? Does it return the number of entries entered? That is, if you have just entered 2 items, does it return 2? Does it return some static class variable that holds the number of items entered?

(As a side design note, does it really make sense that a class Item knows how many items have been entered? Does it make sense that a book in the library knows how many times the book has been borrowed?)

If it returns 2, then doesn't index 1 get left unused? On the first run you insert into items[0], on the second run you insert into items[2]. That would fit together with the exception when trying to access index 1, no?

This is all just speculation and guessing on my part, since I cannot test it myself.

Quote:
Originally Posted by fakepoo
our problem is here:

JAVA Code:
//If first time key in date run statement
       				if(first == 0){
       					++first;//Track if is the first record key in
       					items[i] = new Item(itemNumber, itemDesc, sellPrice, quantity);
}

Because when you enter your second item, the value of first is not zero and you never create a new Item(). Then, when you try to access items[1], it is still null, hence the null reference exception.
But he creates a new item later on at
JAVA Code:
if(duplicate == false)//else save record
                        items[entries] = new Item(itemNumber, itemDesc, sellPrice, quantity);
  #4  
Old 10-Jul-2009, 10:00
flar3star flar3star is offline
New Member
 
Join Date: Jul 2009
Posts: 3
flar3star is on a distinguished road

Re: Exception in thread "main" java.lang.NullPointerException


JAVA Code:
public class Item{
	private String itemNumber;
	private String itemDesc;
	private double sellPrice;
	private int quantity;
	private int entries;
	private boolean duplicate = true; //Declaration for equals method
		/*public Item() {*/
	public Item(String itemNumber, String itemDesc, double sellPrice, int quantity) {
    	setItemNumber(itemNumber);
    	setItemDesc(itemDesc);
    	setSellPrice(sellPrice);
    	setQuantity(quantity);
    
    } //Constructor with arguments
    
    private void setItemNumber(String itemNumber){
    	this.itemNumber = itemNumber;
    } //Set method for itemNumber
    
    public String getItemNumber(){
    	return itemNumber;
    } //Get method for itemNumber
    
    private void setItemDesc(String itemDesc){
    	this.itemDesc = itemDesc;
    } //Set method for itemDesc
    
    public String getItemDesc(){
    	return itemDesc;
    } //Get method for ItemDesc
    
   private void setEntries(int entries){
    	this.entries = entries;
    }
   
    public int getEntries(){
    	return entries;
    }
    
    private void setSellPrice(double sellPrice){
    	this.sellPrice = sellPrice;
    } //Set method for sellPrice
    
    public double getSellPrice(){
    	return sellPrice;
    } //Get method for sellPrice 
    
    private void setQuantity(int quantity){
    	this.quantity = quantity;
    } //Set method for quantity
    
    public int getQuantity(){
    	return quantity;
    }
    
    public boolean equals (String itemNumber, String itemDesc, double sellPrice, int quantity) {
    	if(this.itemNumber.equals(itemNumber) == true && this.itemDesc.equals(itemDesc) == true &&
       		this.sellPrice == sellPrice && this.quantity == quantity)
       		return true;
       		
       	else
       		return false;
    }
    
    public boolean searchNumber(String itemNumber) {
    	if(this.itemNumber.equals(itemNumber) == true)
    		return true;
    	
    	else
    		return false;
    }
    	
    		
       			public void makeCopy (String itemNumber, String itemDesc, double sellPrice, int quantity) {
    	
    	setItemNumber(itemNumber);
    	setItemDesc(itemDesc);
    	setSellPrice(sellPrice);
    	setQuantity(quantity);	
    } //Equals method that returns true if two objects are the same
}

item class

and btm is print
JAVA Code:
/**
 * @(#)Calculation.java
 *
 *
 * @author 
 * @version 1.00 2008/7/15
 */


public class Print {

	public static void option () {
    	System.out.println("1. Add new Item ");
    	System.out.println("2. Generate List of Record Entered");
    	System.out.println("3. Search Record by Item Number");
    	System.out.println("4. Modifiy Record");
    	System.out.println("5. Updated Quantity on Hand");    	
    	System.out.println("6. Exit");
    	System.out.println();
    	System.out.print("Enter your choice : ");
    }
    
    public static void sample () {
    	System.out.println("Sample of Correct Method of Input");
    	System.out.println("***********************************************************");
    	System.out.println("Enter Item Number         : 12345 ");
    	System.out.println("Enter Item Description    : Eraser");
    	System.out.println("Enter Selling Price 	  : RM1.95");
   		System.out.println("Enter Quantity on Hand    : 10");
    	System.out.println("###########################################################\n");
    }
    
    public static void duplicateError () {
    	System.out.println("\nThis record has been entered.");
      	System.out.println("Duplicate record are not allow.\n");
    }
    
    public static void createBy () {
    	System.out.println("\n\nThank you for using the program.");
    	System.out.println("Created by Sanjay a/l s.Sasietharan and Dinesh Philip Mathew, Q5.");
    }
}
  #5  
Old 10-Jul-2009, 12:54
Kimmo Kimmo is offline
Member
 
Join Date: Mar 2007
Location: Finland
Posts: 285
Kimmo is a jewel in the roughKimmo is a jewel in the roughKimmo is a jewel in the rough

Re: Exception in thread "main" java.lang.NullPointerException


... And? What were the results from mine and fakepoo's suggestions?
  #6  
Old 12-Jul-2009, 04:15
flar3star flar3star is offline
New Member
 
Join Date: Jul 2009
Posts: 3
flar3star is on a distinguished road

Re: Exception in thread "main" java.lang.NullPointerException


sorry for the late reply

thanks to both of u i've finally finished up that part =D

though i have a small confusing error as in below.

JAVA Code:
import java.util.Scanner;
public class RunItem {
        static Scanner input = new Scanner(System.in);
        static Item items[] = new Item[100];
        //static items[0] = new Item();
        static int first = 0;
    /**
     * Creates a new instance of <code>RunItem</code>.
     */
    public RunItem() {
    }
   
    public static void main(String[] args) {
        // TODO code application logic here
        
        
        int optionMenu;
        
        
        String optionContinue;
        do{
    		Print.option();//print menu
    		optionMenu = input.nextInt();
    				
			if(optionMenu == 1)	
    			Add();
    			
    		else if(optionMenu == 2)
    			List();
    			
    		else if(optionMenu == 3)
    			Search();
    			
    		else if(optionMenu == 4)
    			Modifiy();
    			
    		else if (optionMenu == 5)
    			Transaction();
    				
    		else if (optionMenu == 6)
    			Stock();
    				
    		else if (optionMenu == 7)
    			Details();
    				
    		else if(optionMenu == 8)
    			break;
  		
  		
  			System.out.print("Do you want to continue (Y/N)?");
			optionContinue = input.next();
			
			System.out.println();
    	}while(optionContinue.equals("N") == false && optionContinue.equals("n") == false);
    	
    	
    	Print.createBy();
    }
    
    public static void Add() {
    	boolean duplicate = false;
    	
    	System.out.println("\nAdd New Item");
    	System.out.print("No. of Entries : ");//Record number of entries at a time
    	int looping = input.nextInt();
    	
    	System.out.println();
    	Print.sample();
    	
    	for(int i = 0; i < looping; ++i) {
    		System.out.print("Enter item number        : ");
       		input.useDelimiter("\n");
       		String itemNumber = input.next();
       				
       		System.out.print("Enter item description   : ");
       		input.useDelimiter("\n");
       		String itemDesc = input.next();
       			
       		System.out.print("Enter selling price      : RM ");
       		double sellPrice = input.nextDouble();
       		
       		System.out.print("Enter quantity           : ");
       		int quantity = input.nextInt();
       				
       		System.out.println("===========================================================");
    		
    		if(first == 0){
    			items[0] = new Item(itemNumber, itemDesc, sellPrice, quantity);
    			first = 1;
    			items[0].setEntries(1);
    		}
    		else{
    			int entries = items[0].getEntries();
    		
    			for(int j=0; j<entries; ++j){
       				
       				duplicate = items[j].equals(itemNumber, itemDesc, sellPrice, quantity);//Check for duplication of entries
       						
       				if(duplicate == true) {
       					
       					Print.duplicateError();
       					--i;
       					--looping;
       					break;
       				}
       			}
    			if(duplicate == false){
    				/*System.out.println("save in no."+entries);
    				System.out.println("i counter no."+i);*/
    				if(first == 1){
    					items[i] = new Item(itemNumber, itemDesc, sellPrice, quantity);    					
    				}else{
    					items[entries] = new Item(itemNumber, itemDesc, sellPrice, quantity);
    					items[0].setEntries(entries+1);
    				}
    			}
    				
    		}
    		
    	}
    	if(first==1)
    		items[0].setEntries(looping);
    		
    	first = 2;
    }
    
    public static void List() {
    	System.out.println("Generate List of Record Entered");
    	int entries = items[0].getEntries();//Get number of record entered
    	
    	for(int i=0; i<entries; ++i) {
    		System.out.println(i+1 + ". " + items[i].getItemNumber());
    	}
   		System.out.print("\nItem Number no : ");
   		int searchPerson = input.nextInt();
   		searchPerson = searchPerson - 1;
   		//Print record searched
   		System.out.println("Item Number       : " + items[searchPerson].getItemNumber());
   		System.out.println("Item Description  : " + items[searchPerson].getItemDesc());
   		System.out.println("Selling Price     : RM " + items[searchPerson].getSellPrice());
   		System.out.println("Quantity          : " + items[searchPerson].getQuantity());
    }
    
    public static void Search(){
    	System.out.println("Search Record by Number");
    	System.out.print("Item Number : ");
    	input.useDelimiter("\n");
    	String searchName = input.next();
    	boolean result = false;
    	int entries = items[0].getEntries();//Get entries of record entered
    	
    	for(int i=0; i<entries; ++i) {
    		
    		boolean equals = items[i].searchName(searchName);//Search record
    		
    		if(equals == true) {//Print if record found
    			System.out.println("\nRecord no. " + (i+1));
    			System.out.println("Item Number       : " + items[i].getItemNumber());
    			System.out.println("Item Description  : " + items[i].getItemDesc());
    			System.out.println("Selling Price     : " + items[i].getSellPrice());
    			System.out.println("Quantity          : RM " + items[i].getQuantity());
    					
    			result = true;//Track if the record is found or not
    		}
    		else
    			result = false;//Track if the record is found or not
    		}
    			
   		if(result == false)//Print if record not found
   			System.out.println("Record not found.");
    }
    
    public static void Modifiy(){
    	System.out.print("Entry No. : ");
    	int searchEntry = input.nextInt();
    	
    	boolean duplicate = true;
    	
    	System.out.print("\n\nEnter Item Number      : ");
       	input.useDelimiter("\n");
       	String itemNumber = input.next();
       			
       	System.out.print("Enter Item Description      : ");
       	input.useDelimiter("\n");
       	String itemDesc = input.next();
       			
       	System.out.print("Enter Selling Price : ");
       	double sellPrice = input.nextDouble();
       			
       	System.out.print("Enter Quantity       : ");
       	int quantity = input.nextInt();
       			
       	int entries = items[0].getEntries();//Retrieve record entered
       			//Check for duplication
       	for(int i = 0; i<entries; ++i) {
       		duplicate = items[i].equals(itemNumber, itemDesc, sellPrice, quantity);
       	}
       			
       	if(duplicate == true)//print if duplicated record are found
       		Print.duplicateError();
       			
       	else//Save if it not a duplicated record
       		items[searchEntry-1].makeCopy(itemNumber, itemDesc, sellPrice, quantity);
    }
    public static void Transaction(){
    	 int entries = items[0].getEntries();
   			for(int i=0; i<entries; ++i) {
    		System.out.println(i+1 + ". " + items[i].getItemNumber());
    	}
    		System.out.print("\nItem Number no : ");
   		int searchPerson = input.nextInt();
    	
    
    	System.out.print("Enter the amount of items to be bought : ");
    	int amount = input.nextInt();
    	
    	int remainding = ( items[0].quantity - amount);
    	
    	System.out.println("The remainding items is : "+remainding);
    	
       	}
       	public static void Stock() {
       		int entries = items[0].getEntries();
   			for(int i=0; i<entries; ++i) {
    		System.out.println(i+1 + ". " + items[i].getItemNumber());
    	}
    	System.out.print("\nItem Number no : ");
   		int searchPerson = input.nextInt();
    	
    	System.out.print("Please key in the added stock number : ");
    	int addStock = input.nextInt();
		System.out.println("You have added "+addStock+" to the item");

		}
		public static void Details() {
			int entries = items[0].getEntries();
			//System.out.println("No.\tItem Number\tItem Description\tSelling Price\tQuantity On Hand");
   			for(int i=0; i<entries; ++i) {
    		System.out.println("\n"+i+1 + ".\n Item Number      :" + items[i].getItemNumber()+"\n Item Description :"+items[i].getItemDesc()+"\n Selling Price    :RM"+items[i].getSellPrice()+"\n Quantity         :"+items[i].getQuantity());
    	}
    	

		}
}



from the menu num 5 , 6 which are

public static void Transaction(){

and

public static void Stock() {

i've able to save the information but how do i update them into the array like how modify module does? im lost in that part , after that all my problem is solved
  #7  
Old 16-Jul-2009, 13:26
Kimmo Kimmo is offline
Member
 
Join Date: Mar 2007
Location: Finland
Posts: 285
Kimmo is a jewel in the roughKimmo is a jewel in the roughKimmo is a jewel in the rough

Re: Exception in thread "main" java.lang.NullPointerException


Quote:
Originally Posted by flar3star
sorry for the late reply
Likewise.
Quote:
i've able to save the information but how do i update them into the array like how modify module does? im lost in that part , after that all my problem is solved
I'm not exactly sure what you mean. Do you mean, for example, that item[3] has an itemNumber value of "55" and you want to replace that Item with another (or replace just the itemNumber)?

You already have setItemNumber etc. with which you can do this. Other than that, and I don't know much Java, you should be able to just assign another Item object into it's place. I don't know if you have to define some special member function for this to work, but I don't think so.
JAVA Code:
item[45] = new Item("this", "that" /*...*/);
 
 

Recent GIDBlogProgramming ebook direct download available by crystalattice

Thread Tools Search this Thread
Search this Thread:

Advanced Search
Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Forum Jump

Similar Threads
Thread Thread Starter Forum Replies Last Post
Exception in thread "main" java.lang.NullPointerException valley1girl Java Forum 12 18-Jun-2009 13:32
Exception in thread "main" java.lang.NullPointerException gedcraw555 Java Forum 3 25-Feb-2008 09:22
Exception in thread "main" java.lang.NullPointerException Magelloo Java Forum 3 06-May-2007 00:01
Thread Stopping Exception Gix .NET Forum 12 28-Nov-2006 05:30
please help in solving: Exception in thread "main" java.lang.nullpointerexception vkiran_v Java Forum 8 09-May-2006 08:06

Network Sites: GIDNetwork · GIDWebHosts · GIDSearch · Learning Journal by J de Silva, The

All times are GMT -6. The time now is 02:26.


vBulletin, Copyright © 2000 - 2009, Jelsoft Enterprises Ltd.