Reputation: 152
So i am calling a method makeCard(String info) from another class. It works fine the first time it runs through but the second time i call on the method it seems to run twice which creates a StringIndexOutOfBoundsException runtime error and i can't seem to figure out why. I am a bit new to Java so i may be missing something obvious but the logic in my head says it should only run once if called once. Hopefully someone can point out my error.
Here is the method:
public void makeCard(String info){
cInfo = new StringBuffer(info);
int i = 0;
while(cInfo.charAt(i)== ' '){
cInfo.deleteCharAt(i);
}
while(cInfo.charAt(cInfo.length()-1)== ' '){
cInfo.deleteCharAt(cInfo.length()-1);
i--;
}
seperateValues();
makeObject();
}
and here is where it is called:
@Override
public void actionPerformed(ActionEvent e) {
MainWindow mw = new MainWindow();
CardBreakdown cb = new CardBreakdown();
if("submit".equals(e.getActionCommand())){
cb.makeCard(cardInfo.getText());
mw.removeAddPanel();
cardInfo.setText("");
}
}
Thank you in advance for any help you can provide
this is the error: Exception in thread "AWT-EventQueue-0" java.lang.StringIndexOutOfBoundsException: String index out of range: 0
Upvotes: 1
Views: 1317
Reputation: 10285
What if info was empty or null? Then cInfo.charAt(0) will return the error you are getting. You should a null or empty check at the start of your makeCard method
Upvotes: 1
Reputation: 881113
The first thing I would be doing is replacing those two while
loops in makeCard()
with a simple call to String.trim()
- that function will remove leading and trailing whitespace for you.
You should generally always prefer a library call to crafting your own functions, especially functions that may have a rather fatal flaw when, for example, handling empty strings or strings which consist only of spaces :-)
There is no checking in either of your loops for the case where the string is or becomes empty, meaning that charAt
will complain bitterly.
Upvotes: 3
Reputation: 77167
Your code is unnecessarily convoluted for simply removing all occurrences of the space character from a string. Instead:
cInfo = info.trim();
Upvotes: 0