This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 9 years ago.
At first there was an issue removing an element in an arraylist if it was the only one on the list but now there is an exception issue when deleting the last position of the arraylist. What is the best way to deal with this?
edit: Looking back, checking if it is the last element and putting in a dummy element to hold the only spot would work.
the code:
public void deleteCustomer(){
String id = null;
boolean c = false; //true if id is found
int remember = 0; //Remembers the deleted index
id = JOptionPane.showInputDialog(null,"input the if of whome you want to delete",
"input id", JOptionPane.PLAIN_MESSAGE);
int id2 = Integer.parseInt(id); //new int id.
for(int i = 0; i < customers.size(); i++){
if(id2 == customers.get(i).getID()){
if(customers.size() == 1){
System.out.println("test one person");
customers.get(i).setDate(null);
customers.get(i).setID(0);
customers.get(i).setName(null);
customers.get(i).setPeople(0);
}
else{
customers.remove(i);
}
c = true;
remember = i;
if(c == true)
break;
}
}
if(c == true){
int i1 = JOptionPane.showConfirmDialog(null,"the customer "
+ customers.get(remember).getName() + " has been deleted.",
"input people", JOptionPane.PLAIN_MESSAGE);
}
else{
int i1 = JOptionPane.showConfirmDialog(null,"the customer could not be found," +
" please check your id",
"input people", JOptionPane.PLAIN_MESSAGE);
}
}
the error
Exception in thread "AWT-EventQueue-0" java.lang.IndexOutOfBoundsException: Index: 1, Size: 1
at java.util.ArrayList.rangeCheck(Unknown Source)
at java.util.ArrayList.get(Unknown Source)
at MainFrame.deleteCustomer(MainFrame.java:360)
at MainFrame$4.actionPerformed(MainFrame.java:170)
at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
at java.awt.Component.processMouseEvent(Unknown Source)
at javax.swing.JComponent.processMouseEvent(Unknown Source)
at java.awt.Component.processEvent(Unknown Source)
at java.awt.Container.processEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Window.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$200(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)
Don't remove elements from a collection while iterating over it with a for loop. Use an iterator instead which in most cases implements the remove method.
Iterator<Customer> it = customers.iterator();
while(it.hasNext()) {
if(it.next().getId() == id2) {
it.remove();
}
}
That's because you already removed one value, but the initial value in the condition (customer.size()) remains the same. So, the ACTUAL size of the list is 1, even though in the beginning was 2 or more.
What I would suggest is that instead of the for loop you use the iterator:
Iterator it = customers.iterator();
while (iterator.hasNext()) {
Customer customer= (Customer) it.next();
//do stuff with the customer
//remove the customer
it.remove();
}
there's a problem in your output.
After deleting the element with index i, you remember i.
int i1 = JOptionPane.showConfirmDialog(null,"the customer "
+ customers.get(remember).getName() + " has been deleted.",
"input people", JOptionPane.PLAIN_MESSAGE);
This piece of code, therefore, tries to access a deleted element from the list to get the name.
I would say you rewrite your method with the suggestions given by all previous answers. Something like this:
public void deleteCustomer(){
String id = null;
int remember = 0; //Remembers the deleted index
id = JOptionPane.showInputDialog(null,"input the id of whome you want to delete",
"input id", JOptionPane.PLAIN_MESSAGE);
int id2 = Integer.parseInt(id); //new int id.
Iterator<Customer> itr = customers.iterator();
while(itr.hasNext()){
Customer thisCustomer = itr.next();
if(id2 == thisCustomer.getID()){
customers.remove(thisCustomer);
break;
}
remember++;
}
if(remember < customers.size()){
JOptionPane.showConfirmDialog(null,"the customer has been deleted.",
"input people", JOptionPane.PLAIN_MESSAGE);
}
else{
JOptionPane.showConfirmDialog(null,"the customer could not be found," +
" please check your id",
"input people", JOptionPane.PLAIN_MESSAGE);
}
}
Related
I am creating a simple Calculator. Whenever i try to perform any operation it enters into catch block. here is code. textFields are as follows:
textfield(to show calculation),textField1(to enter operand),textfield_1(to show Solution)
button = new JButton("+");
button.setForeground(Color.BLACK);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try{
ans=Double.parseDouble(textField1.getText());
s=Double.toString(ans)+"+";
textField.setText(s);
reset();
operand=Double.parseDouble(textField1.getText());
ans+=operand;
textField_1.setText(Double.toString(ans));
}catch(Exception x){
JOptionPane.showMessageDialog(null, "Please Enter a valid argument");
}
}
});
button.setBounds(43, 115, 89, 23);
frame.getContentPane().add(button);
button.setToolTipText("ADDITION");
//reset textField1
public void reset(){
textField1.setText("");
}
//............//
java.lang.NumberFormatException: empty String
at sun.misc.FloatingDecimal.readJavaFormatString(Unknown Source)
at sun.misc.FloatingDecimal.parseDouble(Unknown Source)
at java.lang.Double.parseDouble(Unknown Source)
at gui.Calcu$2.actionPerformed(Calcu.java:92)
at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
at java.awt.AWTEventMulticaster.mouseReleased(Unknown Source)
at java.awt.Component.processMouseEvent(Unknown Source)
at javax.swing.JComponent.processMouseEvent(Unknown Source)
at java.awt.Component.processEvent(Unknown Source)
at java.awt.Container.processEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Window.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$500(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)
Your problem is here:
reset();//this makes the textField1 hold an empty String
operand=Double.parseDouble(textField1.getText());
So when you are trying to read and parse a Double from it you are geting a NumberFormatException because you can not convert an empty String into a Double.
One solution to your problem is to create a second JTextField and let the user write the first number he wants to add to the first textField and the second one to the second.Then, when he presses the button to see the result read each number separately, process them and show the result to the screen(either on one of your two textFileds or you could use a third one to display the result).
On the other hand, if you want to have a single textField to handle the user input, you could declare a variable sum outside of all the methods(make it global) and each time you press the "+" button add the value to sum and when the user is done typing numbers just display its String value to the screen.
Additional information on how the event-driven programming works.
Try below code in your button click listner,
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try{
final double val1 = Double.parseDouble(textField1.getText());
ans = val1;
s = Double.toString(ans) + "+";
textField.setText(s);
reset();
operand = val1;
ans += operand;
textField_1.setText(Double.toString(ans));
}catch(Exception x){
JOptionPane.showMessageDialog(null, "Please Enter a valid argument");
}
}
});
Hello all I am experiencing issues with my JOptionPane.showInputDialog input field.
The issue i am experiencing that is when the cancel button is selected or the OK button is selected with empty or with categorical i am greeted with an error. Any suggestions.
My first attempt at fixing this i changed the c int into an interger therefore i could use an if statement along with null such as
Integer cInterger = new Integer(c);
if (cInterger.equals(null)){
return;}
Along with
cInterger == null
cInterger !=null
But to no avail
int a = 0; //
int b = 0; //
int c = 0; //
if (selected) {
if (command.equals("amount")) {
Scanner readFile = null;
try {
readFile = new Scanner(new FileReader("BANK.txt"));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String account = "";
account = readFile.nextLine();
String amount = JOptionPane.showInputDialog(frame,"Enter an amount"); //assign user input to string amount
a= Integer.parseInt(account); //conversion of scanned string to int for easy subtraction
b= Integer.parseInt(amount);
c = a-b;
try {
if( c == 0){
JOptionPane.showMessageDialog(null,"Granted.","Granted",JOptionPane.WARNING_MESSAGE);}
else if (c > 0){
JOptionPane.showMessageDialog(null,"Granted.","Granted",JOptionPane.INFORMATION_MESSAGE); }
else{
JOptionPane.showMessageDialog(null,"Denied.","Denied",JOptionPane.ERROR_MESSAGE);}
Resulting errors
Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: null
at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at Options$1MyItemListener.itemStateChanged(Options.java:58)
at javax.swing.AbstractButton.fireItemStateChanged(Unknown Source)
at javax.swing.AbstractButton$Handler.itemStateChanged(Unknown Source)
at javax.swing.DefaultButtonModel.fireItemStateChanged(Unknown Source)
at javax.swing.JToggleButton$ToggleButtonModel.setSelected(Unknown Source)
at javax.swing.ButtonGroup.setSelected(Unknown Source)
at javax.swing.JToggleButton$ToggleButtonModel.setSelected(Unknown Source)
at javax.swing.JToggleButton$ToggleButtonModel.setPressed(Unknown Source)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
at java.awt.Component.processMouseEvent(Unknown Source)
at javax.swing.JComponent.processMouseEvent(Unknown Source)
at java.awt.Component.processEvent(Unknown Source)
at java.awt.Container.processEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Window.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$400(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)
If you take a look at the JavaDocs, you will find that
Returns: user's input, or null meaning the user canceled the input
So attempting to parse null makes no sense, instead you should be using something like...
if (amount != null) {
a = Integer.parseInt(amount);
//...
Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: For input string: "" seems reasonably obvious.
if (amount != null) {
if (amount.trim().length() > 0) {
//...
} else {
JOptionPane.showMessageDialog(frame, "The amount you entered is invalid");
}
You should also check the account value as well
I'm attempting to accept 5 numbers in a textField from the user, in order to sort them using different methods (bubbleSort, mergeSort, quickSort). Unfortunately, I keep having "java.lang.NullPointerException" thrown. I've looked around a bit, and the closest I could find to my issue is NumberFormatException when attempting to parse string as an integer, but that was simply due to an empty space. I threw in a .trim() just for good measure though, to no avail.
public class SortWindow {
private JFrame frame;
private JTextField textFieldInput;
private String[] list;
private int[] numList;
private static JTextArea textAreaOutput;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
SortWindow window = new SortWindow();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public SortWindow() {
initialize();
}
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
//Buttons
JButton buttonBubble = new JButton("Bubble");
buttonBubble.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
textAreaOutput.setText("");
list = textFieldInput.getText().split(" ");
numList[0] = Integer.parseInt(list[0].trim());
for (int i = 0; i < list.length; i++){
numList[i] = Integer.parseInt(list[i]);
}
bubbleSort(numList);
}
});
buttonBubble.setBounds(12, 13, 115, 40);
frame.getContentPane().add(buttonBubble);
//Text Fields
textFieldInput = new JTextField(5);
textFieldInput.setBounds(177, 13, 243, 40);
frame.getContentPane().add(textFieldInput);
textFieldInput.setColumns(10);
textAreaOutput = new JTextArea();
textAreaOutput.setLineWrap(true);
textAreaOutput.setText("In the box above, enter 5 numbers separated by spaces.");
textAreaOutput.setEditable(false);
textAreaOutput.setBounds(177, 66, 243, 176);
frame.getContentPane().add(textAreaOutput);
}
}
list is an array of Strings, and when I enter 1 2 3 4 5 (or any other combination - I even tried just entering a single digit and seeing what happened using my second line, but it still threw the exception) into the textField in my GUI, it stores it correctly within the String array, and I can successfully print the individual Strings within it perfectly fine using System.out.print(). My problem only arises when I attempt to use any of the following four lines (I only included the second line to make sure there wasn't something wrong with my for loop).
I can provide the rest of my code if needed, but I figured I'd start with this, since I can't think of anything else that would be affecting it.
EDIT: Added a much larger part of my class to the OP. The exception is thrown in line 60, which is:
numList[0] = Integer.parseInt(list[0].trim());
EDIT2: As requested, this is what I am given.
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at SortWindow$2.actionPerformed(SortWindow.java:60)
at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
at java.awt.Component.processMouseEvent(Unknown Source)
at javax.swing.JComponent.processMouseEvent(Unknown Source)
at java.awt.Component.processEvent(Unknown Source)
at java.awt.Container.processEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Window.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$200(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)
your numList size might not been initialized. you can try like this and see if its okay:
int[] numList=new int[5];
String[] list = textFieldInput.getText().split(" ");
for (int i = 0; i < list.length; i++){
numList[i] = Integer.parseInt(list[i]);
}
System.out.println(Arrays.toString(numList));
That Exception means that the Item in your list is Empty (has value of null), check your list items the problem is there, and not in the parsing part!
try :
System.out.println(list[0]);
and watch the output.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
I have this code, which creates a textfield and a button to let the user search for data in an array:
//Creates a form to search data, list for it and buttons to sort the list.
rightPanel.add(Box.createRigidArea(new Dimension(20, 20)));
final TextField searchTextField;
searchTextField = new TextField ();
rightPanel.add(searchTextField);
rightPanel.add(Box.createRigidArea(new Dimension(20, 20)));
JButton searchConfirmButton = new JButton("Search");
rightPanel.add(searchConfirmButton);
searchConfirmButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
try {
search = searchTextField.getText();
int index = Arrays.asList(data).indexOf(search);
for (String result : data) {
if (result.contains(search)) {
System.out.println(result);
System.out.println(index);
}
}
} catch (NullPointerException e1) {
}
}
});
But whenever I search for the data, whether it exists or not, the program returns me an nullpointerexception with the following content:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at program.Program$4$1.actionPerformed(Program.java:233)
at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
at java.awt.Component.processMouseEvent(Unknown Source)
at javax.swing.JComponent.processMouseEvent(Unknown Source)
at java.awt.Component.processEvent(Unknown Source)
at java.awt.Container.processEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Window.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$200(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)
In this case, row 233 contains this line if (result.contains(search)) {
data looks like an array type that can hold data values or null pointers. You should try:
System.out.println("Found index: " + index);
for (String result : data) {
if (result != null && result.contains(search)) {
System.out.println("Found result: " + result);
}
//If you are still confused than the right else here will help.
}
If, for example, you split a string with two spaces in a row by space, then depending on your function parameters to split(), you can end up with an empty string in that location and you need to skip it effectively.
This is the method called when the player has to be removed from the game. Both these methods are in different classes.
GameboardGUI class
Vector<Player> players = new Vector<Player>();
public void removePlayerFromGame(Player playerToRemove)
{
//go through the playerToRemove's properties and reset all their variables
for(int i = 0; i < playerToRemove.getPropertiesOwned().size(); i++)
{
//code to reset the player's properties to an unowned/unmodified state
}
//same with transports
for(int i = 0; i < playerToRemove.getTransportsOwned().size(); i++)
{
//code to reset the player's transports to an unowned/unmodified state
}
//just updating the vector based on the playerToRemove's position
if(players.get(0) == playerToRemove)
{
players.remove(playerToRemove);
updatePlayerInformation();
}
else
{
players.remove(playerToRemove);
updatePlayerVector(players);
updatePlayerInformation();
}
}
This is how the method is called:
If the current player (fromMe) lands on a property and cant afford to pay the rent (i.e. their balance reaches 0 as a result of takefrombalance(1200);, currently hardcoded to 1200 to make testing easier) they are removed in the if statement if(fromMe.isBankrupt())
Property Class
GameboardGUI gui = new GameboardGUI();
public void payRent(Player fromMe, Player toYou, int rent)
{
//remove rent from the current player
fromMe.takeFromBalance(1200);
//add it to the owner
toYou.addToBalance(rent);
GameboardGUI.addGameFeedMessage(fromMe.getName() + " has paid " + rent + " in rent to " + toYou.getName());
GameboardGUI.addGameFeedMessage(toYou.getName() + "'s balance is now " + toYou.getBalance());
if(fromMe.isBankrupt())
{
//THIS IS THE CALL THAT THROWS THE NullPointerException
gui.removePlayerFromGame(fromMe);
}
else
{
GameboardGUI.addGameFeedMessage(fromMe.getName() + "'s balance is now " + fromMe.getBalance());
}
}
Here is the stack trace when the line is reached:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at PropertyTile.payRent(PropertyTile.java:254)
at PropertyTile.landedOnProperty(PropertyTile.java:239)
at GameboardGUI.playerHasLanded(GameboardGUI.java:1905)
at Player.setPosition(Player.java:82)
at Player.movePlayer(Player.java:101)
at GameboardGUI$11.actionPerformed(GameboardGUI.java:1536)
at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
at java.awt.Component.processMouseEvent(Unknown Source)
at javax.swing.JComponent.processMouseEvent(Unknown Source)
at java.awt.Component.processEvent(Unknown Source)
at java.awt.Container.processEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Window.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$000(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)
It's really hard to help you without a stacktrace and the line numbers for your code, but we're trying.
If that's really the line (and not actually within removePlayerFromGame), the member gui hasn't been initialized.
Of course, if it's not that line, it could simply be that playerToRemove is null, and the NullPointerException is actually happening a couple of lines above.
Or, another possibility is that it's happening within removePlayerFromGame, in which case the most likely case is that playerToRemove hasn't been properly set up - that its getPropertiesOwned() or getTransportsOwned() methods are returning null.
I would add the following two lines, as a first step to see what happens:
if(fromMe==null)
System.out.println("from me is null");
if(gui == null)
System.out.println("gui is null");
gui.removePlayerFromGame(fromMe);
One of the two object references is null causing the exception.
Otherwise, the method removePlayerFromGame is doing something, but I don't think that would be the case because the stacktrace would include additional methods.
You say in the code that the Exception is thrown when you reach the line
gui.removePlayerFromGame(fromMe);
However, the top of stacktrace you are showing is Player.movePlayer(), with its bottom at PropertyTile.payRent().
Is this payRent() receiving any parameter? Can you post it source?