no arrays.
hi guys. this is my code. I've been changing it back and forth trying various things but for the most part, this is the general skeleton. really frustrating, have spent about 30 hours on this and still can't get it so it is extremely discouraging. all help will be greatly appreciated.
my question isn't necessarily how to fix the error but to see if my approach makes sense. if what I've done thus far can actually be completed or if my code has to be rewritten or just slightly modified to work. I have scrapped the whole thing a total of 3 times and started from scratch and now I am here.
import java.util.*; class WhiteSpace { public static void main(String[] args) { Scanner scan = new Scanner(System.in); String text; //variable for user's input String cTrim; System.out.println("enter desired width"); int width = scan.nextInt(); //desired width input System.out.println("enter desired phrase"); scan.nextLine(); String keyboard = scan.nextLine(); //takes a line 2b formatted cTrim = keyboard.replaceAll("^\\s+", ""); //compresses whitespace text = cTrim.replaceAll("\\s+", " "); System.out.println(text.length()); int i = 0; int lastspace = -1; int linestart = 0; int lastprinted = 0; int k = 0; // hello what are you d // oing // lastspace = 5, 10, 14, 18 // at i = 20, lastspace = 18 if (text.length() < width) System.out.println(text); else { while (i < text.length()) { while (i < linestart + width + 1) // while i < 21 { if (text.charAt(i) == ' ') lastspace = i; //lastspace is 18 if (i > linestart + width - 1) //i is 20 if bigger than 19 { if (lastspace != -1) // 18 { for (i = lastprinted; i < lastspace; i++) // i = 0; < 18 { System.out.print(text.charAt(i)); // 0 - 17 hello how are you k++; } if (i == lastspace) // i = 17 System.out.println(); i = lastprinted + k; // i would be 17 + 0 } } i++; } linestart = lastspace + 1; //linestart is now 19 lastspace = -1; //lastspace no longer 18 lastprinted = i + 1; //last printed is 18 } } } }
I've pretty much been testing it with a width of 20 and the input of "hello how are you doing".
my desired output is as follows:
so my comments are just for me to keep track of where i currently is to be accurate.hello how are you doing
I'm trying to do left justification. my idea here is that I detect the last space in a line and println() at that spot so that the next printed char is in a new line. then I want to detect the last space in that 2nd line and so forth and so forth. my problem is figuring out how I can print all the characters while not screwing up the incrementing i that has to continue to discover the last space in a line. hope that makes sense. all help will be greatly appreciated. thanks in advance.