srmjr srmjr - 4 months ago 8
Java Question

Two problems, using charAt for undefined input and looping output

So, I posted this nearly identical code yesterday, asking about how to leave the punctuation at the end of a reversed sentence after using

.split
. I'm still struggling with it, but I'm also having another issue with the same code: And here is my screen shot http://i.stack.imgur.com/peiEA.png

import java.util.Scanner;
import java.util.StringTokenizer; // for splitting


public class MyTokenTester
{
public static void main(String\[\] args)
{
Scanner enter = new Scanner(System.in);
String sentinel = ""; // condition for do...while
String backward = ""; // empty string
char lastChar = '\0';




do
{

System.out.println("Please enter a sentence: ");
String sentence = enter.nextLine();
String\[\] words = sentence.split(" "); // array words gets tokens
// System.out.printf("The string is%s",sentence.substring(sentence.length()));


for (int count = words.length -1; count>=0; count--) // reverse the order and assign backward each token
{
backward += words\[count\] + " ";


}


System.out.println(backward); // print original sentence in reverse order

System.out.println("Hit any key to continue or type 'quit' to stop now: ");
sentinel = enter.nextLine();
sentinel = sentinel.toLowerCase(); // regardless of case






} while (!sentinel.equals("quit")); // while the sentinel value does not equal quit, continue loop

System.out.println("Programmed by ----");



} // end main



} // end class MyTokenTester][1]][1]


As you guys can probably see my from screen shot, when the user is prompted to add another sentence in, the previous sentence is read back again.

My questions are:


  1. How do I use
    charAt
    to identify a character at an undefined index (user input with varying lengths)

  2. How do I stop my sentence from reading back after the user decides to continue.



Again, as I said, I'd posted this code yesterday, but the thread died and I had additional issues which weren't mentioned in the original post.

Answer

To address part 2, if you want to stop the sentence from reading back previous input, then reset backward to an empty string, because as it stands now, you're constantly adding new words to the variable. So to fix this, add this line of code right before the end of your do-while loop,

backward = "";

To address part 1, if you want to check the last character in a string, then first you have to know what is the last index of this string. Well, a string has indexes from 0 to str.length()-1. So if you want to access the very last character in the user input, simply access the last word in your words array (indexed from 0 to words.length - 1) by doing the following,

words[count].charAt(words[count].length() - 1);

Note that count is simply words.length - 1 so this can be changed to your liking.

Comments