Exception in thread "main" java.lang.NullPointerException
Hello all I need a little help here I am getting this error(Exception in thread "main" java.lang.NullPointerException) on line 12 and not sure why, here is my code
Code:
import javax.swing.JOptionPane;
public class CoffeeDriver
{
public static String names;
public static double prices;
public static void main (String[] args)
{
Item [] names = new Item [5];
Item [] prices = new Item [5];
names[0].setName("Coffee");
names[1].setName("Water");
names[2].setName("Milk");
names[3].setName("Bagel");
names[4].setName("Donut");
prices[0].setPrice(1.00);
prices[1].setPrice(2.00);
prices[2].setPrice(1.50);
prices[3].setPrice(1.25);
prices[4].setPrice(0.75);
String Sort = JOptionPane.showInputDialog(null,"Would you like the menu items sorted by name or price? (n/p)", "Welcome to Wings Coffee Shop",1);
if (Sort == "n")
{
sortName(names);
}
else
sortPrice(prices);
}
public static void sortName( Item [] array)
{
}
public static void sortPrice (Item [] array)
{
int a, b;
Item temp;
int highSubscript = array.length -1;
for(a = 0; a < array.length; ++a)
{
for(b = 0; b < highSubscript; ++b)
{
if(array[b].getPrice() > array[b + 1].getPrice())
{
temp = array[b];
array[b] = array[b + 1];
array[b + 1] = temp;
}
}
}
}
}
Re: Exception in thread "main" java.lang.NullPointerException
I think I may have the solution.
You seem to initializing everything in your main method, which is something I suggest not doing.
Instead make an init() method to do all of that.
Code:
public void init(){
//Initialization
}
Also you create the object arrays outside of the methods like this:
Code:
public class example{
Item[] names;
Item[] prices;
//ect...
Then, inside of your init() initialize the objects:
Code:
public void init(){
names = new Item [5];
prices = new Item [5];
for(int i = 0; i < names.length; i++)
names[i] = new Item();
for(int i = 0; i < prices.length; i++)
prices[i] = new Item();
names[0].setName("Coffee");
names[1].setName("Water");
names[2].setName("Milk");
//ect...
}
This is my first time answering a question, but I'm fairly confident this should help.
Re: Exception in thread "main" java.lang.NullPointerException
Declaring the size of an object array doesn't automatically populate the array with objects of the declared Type.
db
Re: Exception in thread "main" java.lang.NullPointerException
Exactly as Darryl said .... were are u populating names ?. You will have to do something like this.
Code:
Item [] names = new Item [5];
Item item = new Item();
item.setName("Coffee");
names[0] = item;
warm regards
Vinod M