This site requires JavaScript, please enable it in your browser!
Greenfoot back
HolyCheeseCurd
HolyCheeseCurd wrote ...

2017/5/23

Text Splitting.

HolyCheeseCurd HolyCheeseCurd

2017/5/23

#
The objective of this code is to split a string that is over 60 characters into two separate strings, cutting them at a space. So, the issue that I'm having is that, in the second 'for' loop, the value for 'a' is equal to the 'str' in the methods parameters, and I can't figure out why. Any help would be appreciated.
String textPanel_2;
    String textPanel_3;
    String textPanel_4;
    String textPanel_5;
    public String correctText(String str)
    {
        String textPanel_1 = str;
        String remainder = str;
        for (int a = 60; a > 0; a--)
        {
            if (str.charAt(a) == ' ')
            {
                textPanel_1 = str.substring(0, a);
                remainder = str.substring(a + 2, str.length());
                break;
            }
        }
        if (remainder.length() < 60)
        {
            for (int a = remainder.length() - 1; a > 0; a--)
            {
                if (remainder.charAt(a) == ' ')
                {
                    textPanel_2 = remainder.substring(0, a);
                    remainder = remainder.substring(a + 2, str.length());
                }
            }
        }
        return textPanel_1;
    }
danpost danpost

2017/5/23

#
HolyCheeseCurd wrote...
in the second 'for' loop, the value for 'a' is equal to the 'str' in the methods parameters
Impossible. 'a' is an int variable and 'str' is a String variable. They cannot both hold the same value.
danpost danpost

2017/5/23

#
I would have the method return an array of String objects instead of just the first (and having to store the rest of the unknown number of lines in String fields for later use). Also, the 'a+2' in lines 14 and 25 should be 'a+1'. The condition on line 18 seems to be wrong also.
danpost danpost

2017/5/23

#
You also might consider using the lastIndexOf(String, int) method of the String class.
You need to login to post a reply.