I am trying to get my Java program to accept blank lines of text as input, as well as displaying them in the final output.
Basically I have made a word scrambling program, that is supposed to take in an unspecified amount of text from the Scanner, scrambling each word individually except for the first and last letters of each word. I have successfully gotten the scrambling and parsing to work, so no worries there. The last spec that I'm working on, is the fact that the user may hit the "return" button entering in a blank line of text.
So, for example, if someone were to enter: Pizza is my favorite thing to eat
The output would be something like: Pziza is my fovaitre tnhig to eat
That works perfectly on one line, but if someone were to enter:
I
Like
Animals
Only the last line gets printed and scrambled: aimnlas
I have tried a few different suggestion I found through research, but most are suggestions for file reading and other things that haven't worked out for me. This is what I'm doing now:...
Scanner input = new Scanner(System.in);
String text = "";
System.out.println("Enter text to scramble: ");
while(input.hasNextLine()){
text = input.next();
}
System.out.println(scramble(text));
Any help would be greatly appreciated. Thanks everyone =)
EDIT: OK I'm thinking something I did in my scramble method may be what's preventing me from allowing blank lines. I've looked it over and can't seem to pinpoint it, so if someone could please take a look and let me know what you think I would appreciate it =)
private static String scramble(String txt) {
StringTokenizer st = new StringTokenizer(txt, " ,.!?()-+/*=%@#$&:;\"'", true);
String[] tokens = new String[st.countTokens()];
String scrambled = "";
int letter = 0;
int wordlength = 0;
char[] temp;
while(st.hasMoreTokens()) {
tokens[letter] = st.nextToken();
letter++;
}
for(int i = 0; i < tokens.length; i++) {
if(tokens[i].length() <= 3) {
scrambled += tokens[i];
continue;
}
wordlength = tokens[i].length() - 1;
temp = new char[wordlength + 1];
temp[0] = tokens[i].charAt(0);
temp[wordlength] = tokens[i].charAt(wordlength);
ArrayList<Character> c = new ArrayList<Character>();
for(int j = 1; j < wordlength; j++) {
c.add(tokens[i].charAt(j));
}
Collections.shuffle(c);
String z = new String();
for(Character x:c){
z += x.toString();
}
String output = new String(temp[0] + z + temp[wordlength]);
scrambled += output;
}
return scrambled;
}