简体   繁体   中英

My method is running twice when it is only called once

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

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.

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

Your code is unnecessarily convoluted for simply removing all occurrences of the space character from a string. Instead:

cInfo = info.trim();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM