Quantcast
Channel: Programming Forums
Viewing all articles
Browse latest Browse all 51036

"Margin" formatting

$
0
0
Hello, I am new to Java as well as this forum.

I am an absolute beginner to Java. The program takes a width that the user inputs, and also a line of text (that can't be longer than the width.) The program then removes the spaces in the sentence and works out how many "spare" characters there are in the sentence. The spaces are then placed back in and replaced by dots (.) and the remaining characters are distributed across the spaces as dots also.

It doesn't make much sense when I try to explain it sadly, so here is my code for the program. Hopefully this clarifies the above.

class Main
{
    public static void main(String args[])
    {
        System.out.print("#Enter Line Width:  ");
        int lineWidth = BIO.getInt();

        System.out.print("#Enter Line Text:  ");
        String lineText = BIO.getString();
                  
        while(! lineText.equals("END"))
           {
            String lineLC = lineText.toLowerCase();
            String [] lineSentence = lineText.split(" ");       //Splitting to individual words to be printed

            int count = 0;
            for(int i=0; i<lineLC.length(); i++)
            {
                if(lineLC.charAt(i) == ' ')
                    count++;
            }
            
            String noSpaces = lineLC.replaceAll("\\s+","");

            int gapsCurrently = count;          //How many gaps(Spaces)
            int spacesToAdd = lineWidth - noSpaces.length();      //How many to add to the sentence
            int spacesAddedAtGap = spacesToAdd/gapsCurrently;       //How many spaces added to each gap
            int spaceDistribution = spacesToAdd%gapsCurrently;      //How many spaces to be distributed across the gaps

            for( int i=0; i<lineSentence.length; i++)
            {
                System.out.print(lineSentence[i]);                
                                   
                if(gapsCurrently > i)
                {
                    System.out.print(".");
                }                
                if(spacesToAdd > i)
                {
                    System.out.print(".");
                }
            }    
            
            System.out.print("#Enter Line Text:  ");
            lineText = BIO.getString();
        }               
    }
}


I have tried to methods as my lecturer believes they are easier, but I cannot get my head around them. The last 'for statement' is the problem with the program, I think.

Any suggestions would be grateful, Jingle.

Viewing all articles
Browse latest Browse all 51036

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>