Hello! I'm making a program that formats inputted text based on the line width the user inputs and the type of formatting the user chooses (left-justified, right-justified, centered). I'm not allowed to use arrays for this, so I decided to tokenize the string instead. The problem is, I can't make the next word go down a line after the width of the line has been reached. Here's my code:
import java.io.*; import java.lang.*; import java.util.*; class Format { public static void main (String[]args) { String winput, sinput, finput, output; int winput2 = 0; Console console = System.console(); winput = console.readLine("Please enter the width of the line. This must be less than or equal to 80: "); winput2 = Integer.parseInt(winput); while (winput2 > 80) { winput = console.readLine("Please enter the width of the line. This must be less than or equal to 80: "); winput2 = Integer.parseInt(winput); } sinput = console.readLine("Please enter the text you want to be formatted: "); StringTokenizer sinput2 = new StringTokenizer(sinput); finput = console.readLine("How do you want to format your text? Choose 'L' for left-justified, 'R' for right-justified, 'C' for centered, or 'Q' to quit the program: "); if (finput.equals("L")) { Lformat(winput2, sinput); } else if (finput.equals("R")) { Rformat(winput2, sinput); } } public static void Lformat (int winput, String sinput) { int i, count = 0; for (i=1; i <= winput; i++) { System.out.print("a"); } System.out.println(); StringTokenizer sinput2 = new StringTokenizer(sinput); while(sinput2.hasMoreTokens()) { System.out.print(sinput2.nextToken() + " "); } } public static void Rformat (int winput, String sinput) { System.out.println(sinput); } }
In other words, is it possible to get the length of each individual token so I know how much to increment the variable "count"? Being able to do so would allow me to halt the next token from being printed out on the same line if it exceeds the line width. Thanks in advance!